Here some bits of info about python dictionaries. How to perform loops with them. Extra special beginner stuff. Note that I am a beginner as well. Who knows? It may come in useful for ONE person out there.
Here are some random bits of info about looping through a python Dictionary:
lets have our example dictionary.
myDictionary = {'Key1':'Value1','Key2':'Value2','Key3':'Value3'}
A dictionary is a set of key:value pairs. Some value is associated with some key.
myDictionary['Key1'] would spit out ‘Value1′
Update from a comment below (Paddy):
for key, value in myDictionary.iteritems():
This uses iteritems to access a generator of the key,value pairs – so on a large dictionary you don’t waste memory generating a large intermediate list; and uses tuple assignment to assign to key and value.
Now, if you did a little experimenting, you would see that if you loop through a dictionary you loop through its keys.
for item in myDictionary:
print item
would output each key. ‘Key1′,’Key2′,’Key3′
You could always get access to each value by pulling up the dictionary again and inputting the keys you are individually looping through.:
for item in myDictionary:
print myDictionary[item]
Looping through each SET of items in the dictionary (instead of the key):
a_dictionary.items() returns the dictionary as a list of value pairs (another list).
a_dictionary.items()[0] is therefore valid, and a key would be accessed with a further index.
a_dictionary.items()[0][0] = key
a_dictionary.items()[0][1] = value
for item in myDictionary.items():
print item
will output the pair (‘Key1′,’Value1′), (‘Key2′,’Value2′). If for whatever reason you wanted both key and value for further processing, you could use this to separate them again (except that it has been obsoleted by Paddy’s comment above):
for item in myDictionary.items():
key, value = item
print key
print value
This may be useless to post, but time will tell.
3 responses so far ↓
paddy3118 // May 15, 2008 at 5:17 am |
Hi Ken,
There is also this form which is only a little more advanced:
for key, value in myDictionary.iteritems():
This uses iteritems to access a generator of the key,value pairs – so on a large dictionary you don’t waste memory generating a large intermediate list; and uses tuple assignment to assign to key and value.
- Paddy.
P.S. Welcome to Python!
Lucass // August 13, 2008 at 11:37 am |
Thankyou lots, I’ve been looking for an article like this everywhere!
seba // February 5, 2009 at 11:59 am |
also if you want an iterator for keys you can use in a for statement:
myDictionary.iterkeys()
or if you want an iterator for values:
myDictionary.itervalues()