Python Dictionary

Back To Index

Dictionaries

Introduction to Python Dictionaries

Python dictionaries are the last elementary data structure. Dictionaries consist of pairs of labels, called keys, and associated values. Together these make a key-value pair. We query a dictionary by asking for a key and getting back the corresponding value.

Much like lists, dictionaries have variable length, can store anything, including a mixture of different types of data. Also their elements can be changed. But, dictionaries are unordered.

We denote a dictionary with curly-braces { }. Key-value pairs are separated by commas, and keys are separated from values by a colon.

{key1:value1, key2:value2, key3:value3 … }

In [54]:
my_dictionary = {"name":"Bob", "age":12, "married":False} #make a dictionary with heterogeneous values
In [5]:
my_dictionary["age"] #look up the value corresponding to "age"
Out[5]:
12
In [33]:
#Here we put each key-value pair on separate lines, using comma to tell Python to continue on the next line. 
#Also, we have lists as the values. 
Beatles = {
    "John":["Voice","Guitar","Harmonica","Keyboard","Cowbell"],
    "Paul":["Voice","Bass Guitar","Electric guitar","Acoustic guitar"],
    "George":["Voice","Guitar"],
    "Ringo":["Drums"]
}
Beatles["George"]
Out[33]:
['Voice', 'Guitar']

A problem arrises if we query a dictionary with some key that isn’t present in the dictionary. This happens surprisingly often and makes the program crash.

In [34]:
Beatles["Elvis"]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-34-aac0a5e9169e> in <module>
----> 1 Beatles["Elvis"]

KeyError: 'Elvis'

As a result, we must always protect against the possibility of bad keys. One option is to check if the key is present in the dictionary using the “in” keyword. This lets us decide what to do with bad keys.

In [35]:
proposed_key = "Elvis"
if proposed_key in Beatles:
    print(Beatles[proposed_key])
else:
    print(proposed_key + " is not a Beatle")
Elvis is not a Beatle

Another option is to use get() in place of [ ], which returns None if given a bad key

In [36]:
print(Beatles.get("Ringo"))
['Drums']
In [37]:
print(Beatles.get("Elvis"))
None
In [38]:
#We can modify elements
Beatles["Ringo"] = ["Voice","Drums"] 
Beatles.get("Ringo")
Out[38]:
['Voice', 'Drums']
In [39]:
#We can add new pairs to the dictionary by assigning a value to the dictionary indexed at that key
Beatles["Pete Best"] = ["drums (but badly)"]
Beatles.get("Pete Best")
Out[39]:
['drums (but badly)']
In [40]:
#We can similarly delete pairs using the del operator. 
#But be careful! If you try to delete a key that's present, this will crash!
if "Pete Best" in Beatles:
    del Beatles["Pete Best"] 
In [41]:
#Like lists, we can get the number of key-value pairs using len
len(Beatles)
Out[41]:
4

Some other useful functions:

the keys( ) function returns a list of the keys

the values( ) function returns a list of values

the items( ) function gives a list of (key, value) tuple pairs.

update( ) allows dictionary concatenation.

pop( ) removes a key/value pair and returns the value.

In [69]:
#Items is nice for iterating over a dictionary:
for key,value in my_dictionary.items():
    print(key, value)
age 12
married False
John ['Voice', 'Guitar', 'Harmonica', 'Keyboard', 'Cowbell']
Paul ['Voice', 'Bass Guitar', 'Electric guitar', 'Acoustic guitar']
George ['Voice', 'Guitar']
Ringo ['Voice', 'Drums']
In [55]:
print(len(my_dictionary))
if "name" in my_dictionary:
    print(my_dictionary.pop("name"))
print(len(my_dictionary))
3
Bob
2
In [53]:
#again, we must be careful to not pop a non-existent key. The following won't work
my_dictionary.pop("not a key")
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-53-7aa6087d19de> in <module>
      1 #again, we must be careful to not pop a non-existent key. The following won't work
----> 2 my_dictionary.pop("not a key")

KeyError: 'not a key'
In [56]:
my_dictionary.update(Beatles) #this appends the Beatles dictionary onto my_dictionary
In [58]:
my_dictionary["age"]
Out[58]:
12
In [59]:
my_dictionary["Ringo"]
Out[59]:
['Voice', 'Drums']

Dictionaries and namedtuples

Dictionaries can be easily converted into namedtuples and vice versa

In [60]:
import collections
Point = collections.namedtuple("point_2D","x y")
In [61]:
p_namedtuple = Point(3,4)
In [66]:
#Converting a namedtuple into a dictionary-like object using _asdict()
p_dict = p_namedtuple._asdict()
p_dict
Out[66]:
OrderedDict([('x', 3), ('y', 4)])
In [63]:
#OrderedDicts are used just like dictionary, but they have a definate order--unlike regular dictionaries.
#so if you itterate over one, the keys come out in the same order that they went in.
p_dict['x']
Out[63]:
3
In [64]:
p_dict2 = {'y':8,'x':2} #make a dictionary that we'll turn into a namedtuple
In [70]:
#Converting a dictionary into a namedtuple 
Point(**p_dict2)
Out[70]:
point_2D(x=2, y=8)

Ordering

Dictionaries are unordered, but OrderedDict’s have a constant order. If you compare dicts the order that things went in doesn’t matter, but it does for comparing an OrderedDict.

In [77]:
d = {}
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'
In [78]:
for key in d.keys():
    print(key)
#Depending on the python version, this may or may not produce abcde. In some versions it produces acbed. 
a
b
c
d
e
In [80]:
#Make another similar dictioanry and try to compare it to the previous one. 
d2 = {}
d2['e'] = 'E'
d2['a'] = 'A'
d2['c'] = 'C'
d2['d'] = 'D'
d2['b'] = 'B'
d == d2
Out[80]:
True
In [82]:
od = collections.OrderedDict()
od['a'] = 'A'
od['b'] = 'B'
od['c'] = 'C'
od['d'] = 'D'
od['e'] = 'E'

for key in od.keys():
    print(key)   #This is guaranteed to produce abcde
a
b
c
d
e
In [83]:
od2 = collections.OrderedDict()
od2['e'] = 'E'
od2['a'] = 'A'
od2['c'] = 'C'
od2['d'] = 'D'
od2['b'] = 'B'
od == od2 #Should be false because order matters here and their order is different. 
Out[83]:
False

Back To Index