1.11M Members

how to define a dictionary in python

 
0
 

i want to define a dictionary in python script
i come from china . start to learn python only a week ago
e-mail: zls11610@onestx.com

 
0
 

Some options ...

Empty dictionary d = dict() or d = {} Dictionary with predefined values d = {1: "Hi there", 2: "Good-bye"} Dictionary from a list of tuple pairs

mypairs = ((1,"Hi there"), (2, "Good-bye"))
d = dict(mypairs)

Jeff

 
0
 

Some options ...

Empty dictionary d = dict() or d = {} Dictionary with predefined values d = {1: "Hi there", 2: "Good-bye"} Dictionary from a list of tuple pairs

mypairs = ((1,"Hi there"), (2, "Good-bye"))
d = dict(mypairs)

Jeff

thank you:)

 
0
 

DICTIONARIES

If you don't want to refer to the elements of a collection by their position number but prefer some other type of object as a key, you can use a python dictionary. Let's see an example of one of those: starter = {"John":"soup", "James":"pate", "Joan":"soup"}---->Dictionary by using {...}
There are three elements in that dictionary, and I can refer to starter["James"] and get the string "pate". You'll notice that I set up a dictionary with { ... } (curly braces, but yet again I refer to it using square brackets. If you want to perform an operation on element of a dictionary, you can find out the keys using the keys methodprint starter.keys()
for example since you can't know what the elements are called just be looking at a count of the number of elements as you can with a list or tuple.

# dictionaries
aDictionary = { 1 : "January", 2 : "February", 3 : "March", 4 : "April", 5 : "May", 6 : "June", 7 : "July", 8 : "August", 9 : "September", 10 : "October", 11 : "November" }
aDictionary[ 12 ] = "December" # add item to dictionary


print "The raw dictionary data is:", aDictionary
print "\nThe entries in the dictionary are:"


for item in aDictionary.keys():
print "aDictionary[ ", item, " ] = ", aDictionary[ item ]
Dictionaries
del dictionary[key]
dictionary[key]
dictionary[key] = entry
dictionary.clear()
dictionary.has_key[key]
dictionary.items()
dictionary.keys()
dictionary.values()
len(dictionary)
You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article