The Python Dictionary
Written by Alex Armstrong   
Wednesday, 28 March 2012
Article Index
The Python Dictionary
Getting more complex

 

Key loops

The great thing about a dictionary is that you don't need to scan though its contents to find something. If you want to find Lucy's age you simply write age["lucy"] rather than having to write a loop that examines each element in turn for the correct entry.  However, there are times when you want to process each entry in a dictionary and this needs a loop.

If you are familiar with lists then you will know that you can use:

for x in my_list:

to step through the list with x being set to each value in the list. If you try the same thing with a dictionary:

for x in my_dict:

you will discover that x is set to each key in the dictionary, not each value.

That is, if you simply write a for in loop for a dictionary it is the keys you step through not the values, which is another important difference between a list and a dictionary.

So how can you step through the dictionary values?

There are a number of ways. For example, as you have the key you can simply use:

for key in my_dict:
  print my_dict[key]

Alternatively, you could use a more sophisticated approach via the items() method that every dictionary has:

for key,value in my_dict.items():
  print key, value

For large dictionaries the best way to step through the key or the value is to use the iterkeys or itervalues methods. For example, to step through the keys:

for key in my_dict.iterkeys():
  print key

and to step through the values:

for value in my_dict.itervalues():
  print value

and finally for both:

for key, value in my_dict.iteritems():
  print key,value

When a key doesn't exist

One of the big problem that beginners have is learning to live with the restriction that you can't lookup the value of a key that doesn't exist without causing a runtime error. There are a number of ways around this small difficultly but the simplest is to use the get method. This will by default return none if the key isn't present:

print age.get("mike")

prints None if "mike" isn't in the dictionary. You can also set the default value to use as in:

print age.get("mike", 0)

which would return a zero age for anyone key not in the dictionary.

For more complicated situations, where you have to perform an extended procedure based on the presence of absence of the key, you can use either:

key in dict

or

key not in dict

which evaluate to True or False. 

For example the previous example of get can be written as:

if  "mike" in age:
  print age["mike"]

Complex dictionaries

At this point you have just about all you need to work with dictionaries, although there are some methods that we haven't covered. One idea that sometimes takes a little time to sink in is that the value stored in a dictionary can be almost anything you like. 

For example, suppose you wanted to store the birthday along with the age and perhaps other information about each person. You could do this by simply storing a list in the dictionary.

age["harry"]=[32,"monday"]

Once you have the value associated with a key you can work with it as a perfectly normal example of its type. For example:

list=age["harry"]
print list[1]

or in a more compact but sometimes confusing form:

print age["harry"][1]

both of which would print "monday".

Perhaps the most confusing of all possibilities is the dictionary within a dictionary. For example you might define details dictionary as:

details["price"]=100
details["color"]="red"
details["size"]="big"

and then use it in a products dictionary as:

products={}
products["widget"]=details

which could be written in the style:

products["widget"]={"price":100,
"color":"red",
"size":"big"}

Now to recall the price of a widget you would use:

detail=products["widget"]
price=detail["price"]

or more compactly:

price=products["widget"]["price"]

This sort of complex dictionary can be confusing, especially if you have to write loops that involve outer and inner dictionaries, but it is just a matter of keeping a clear head and understanding what is being stored and retrieved at each level.

Note: All of the ages used in the making of this article were entirely fictional and generated using a random number function.

Related Articles

Arrays in Python

Advanced Python Arrays - Introducing NumPy

The Python Dictionary

Creating The Python UI With Tkinter

Creating The Python UI With Tkinter - The Canvas Widget 

Getting Started with Python

Head First Python (Book Review)

A Concise Introduction to Programming In Python (Book Review)

 

blog comments powered by Disqus

 

Banner

 

To be informed about new articles on I Programmer, subscribe to the RSS feed, follow us on Google+, Twitter, Linkedin or Facebook or sign up for our weekly newsletter.



Last Updated ( Monday, 22 April 2013 )
 
 

   
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.