Major differences vs lists

– Keys are any hashable object (say strings for simplicity)
– Are NOT ordered (a list is by definition ordered)

One way I like to think about them are as little variable containers. The fact that they are wrapped in a container makes them quite useful and versatile since you can easily move the “container” around.

In fact, variables are very much related to dictionaries! Whenever you declare a variable (x=3), that variable is accessible by its string name (‘x’) via the dictionary returned by the builtin function ‘locals()’ or ‘vars()’.

What about getting the values?

Based on what we’ve learned, you could always use the keys you are iterating through to pull the value from the dictionary.

for item in my_dict:
print my_dict[item]

But there are better ways to get the values. Enter the “items” function.

We can ask the dictionary to return key, value pairs via the “items()” function.

for key, value in my_dict.items(): # returns the dictionary as a list of value pairs -- a tuple.
print key, value

More efficient dictionary loops

Calling “my_dict.items()” requires generating the entire list of key-value pairs in-memory. Sometimes, if your dictionary is too large, this can be a severe performance bottleneck. To get around this problem we can create a generator via the “iteritems()” method.

A generator allows you to iterate one item at a time. Only the key and value are pulled into memory for every iteration and immediately discarded. There are methods for returning a key generator and value generator as well.

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

Note that one thing you can’t do with a generator is to delete a key during the generator loop.

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.

Your demonstration of how to loop through keys in a dictionary, or values, or both, and how to use a generator are so fundamental I think they need to be included in the standard python documentation.

This cleared up a whole lot. The one area I debate is whether there is a significant speed boost from using a dictionary and looping, or a list of dictionaries? I often use the latter but don’t know how much slower it is.

i wanted to print an inventory organiced in two columns. object and price lined up like this:
orange____________..5$
apple______________42$
banana____________.230$
pie________________10$
chicken salad_______.15$

hi Yuji,
how do i iterate through a key that is combinational..? i mean, when the key is a set of 3 or 4 different Strings/numbers, then how do i get the data in first two of the set.
eg: dict = { ‘sham, ravi, 098, str123’: ‘ valur1,asdf2,qwer3,…so on’, …….}

Another way to show the output would be to use assert:
assert locals_dict['var1'] == 'val1'

Also in your last example "Generate a dictionary from tuples" you mention using list comprehension to create the dictionary. I see the key_values_pairs list but no list comprehension (or maybe I don't comprehend list comprehension).

As for the list comprehension, yes, I don’t use one in an example, just merely suggesting that creating dictionaries from tuples can be useful because you can create lists of tuples via list comprehensions! Now we have dict comprehensions, but I shy away from those until I’m fully on a 2.7 environment.

Could you tell me if / how I would sort a dictionary in a bespoke order. For example I have a dictionary like:
{‘dob’: ’03/04/1978′,
‘gender’: ‘Male’,
‘age’: ’34’,
‘address’: ‘Rockley Road’,
‘name’: ‘Sean’}

but I want to print for example in the order:
name = Sean
gender = Male
age = 34
dob = 03/04/1978
address = Rockley Road

I was thinking I could use a list with the order I want and iterate through that at the same time as iterating through my dictionary but all the iterating is making me dizzy🙂

Thanks Yuji,
The reason I cant simply do that is because I don’t know up front what the dictionary will contain.
The dictionary is being created at run time based on the contents of an xml file and a user defined list of elements to collate.
Imagine the following xml file:

Sean
34
Blonde
….

….

….

Now I dont know how many ‘Entry’ elements there will be and I also don’t know which elements will be selected.
In my code I have the selected elements in a list of strings and I generate a new list of dictionaries by walking through the xml file and from every ‘Entry’ element pull out the necessary values in a {node_name: value, node_name: value, ….} dictionary.
I want the output to match the order of the list as these are added to the list by the user at run time.

Of course! How frustratingly simple (just like me ^_^) .. Thank you, I will go and have a play with the ordered dictionary.
Glad I’m not stuck using Python 2.6 or older .. is this even possible in older versions?

I just googled for what you meant by ‘subclassing basic types in Python’ and I can agree with you on that .. its pretty amazing.
I am still quite new to programming and Python in particular and I am definitely impressed with the flexibility of this language.
Thanks again for your help earlier. Much appreciated.

This blog is great on dictionary. If you have blogs for other data structures, where could I find them.I have one question regarding converting a list of tuples to dict.
I tried k_v =[(‘key1’, 9), (‘key2’, 10), (‘key3’, 12)]
di = dict(k_v)
but I get the error message as
Traceback (most recent call last):
File “”, line 1, in
TypeError: ‘dict’ object is not callable

Your post came up #4 in my search for “for loop on dictionary python”. and helped me understand how to obtain values when iterating a dictionary and taught me things I haven’t seen before as I learn python. Such as “for key, value in dictionary”.

I hadn’t seen a for loop with 2 iterating values before, nor the iter methods/ key generators.

If you need to sort a Python dictionary often, then check out the sortedcontainers module on Python. It has a fast, pure-Python implementation of a dictionary type that maintains the keys in sorted order.