Codementor Events

Working with Dictionaries in Python

Published Mar 22, 2018Last updated Sep 18, 2018

Hashtables or dictionaries are efficient data structure for structuring/storing data and thankfully it is built into python for our own convenience.
Dictionaries are like lists, but are more general, in lists the indices have to be integers while in dictionaries they can be of almost any type. Dictionaries are like maps, basically what they do is map a key to its value, so in small words dictionaries are just a collection of key-value pairs.

So lets initialize a dictionary

>>>example_dict = dict()
>>>print example_dict
{}   # It outputs an empty dictionary

Now add some key and values to our dictionary

>>>example_dict[“une”]=”one”
>>>example_dict[“deux”]=”two”
>>>example_dict[“trois”]=”three”
>>>print example_dict
>>> {'trois': 'three', 'une': 'one', 'deux': 'two'}

when we printed out our dictionary we can see that the items are not exactly in the order which we added them, anyway that’s why they are also called unordered dictionaries, but this is not a problem at all because dictionaries are not indexed by integers but they use the keys to lookup their corresponding values.
Lets try accessing some of the items in our dictionaries

>>>example_dict[“une”]
‘one’ #the key “une” maps to the value “one”
>>>example_dict[“trois”]
‘three’ #the key “trois” maps to the value “three”

If you try this with a key that’s not in the dictionary you’ll get a KeyError

>>>example_dict[“quarte”]
KeyError: ‘quarte’  #A keyError is raised

Also we can know the number of key-value pairs in our dictionaries with the function len()

>>>len(example_dict)
3 # we have three items in our dictionary

There are some functionality added to the python dictionaries, they are called methods.
If you want to know all of the methods that are built into python dictionaries you’ll use the dir() function

>>>dir(example_dict)
'__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']

Lets say we wanted to see/get all the values or maybe all the keys in our dictionary
there are methods to do that

>>>example_dict.keys()
[“trois”, “une”, “deux”] # returns a list of all of the keys in our dictionary
>>>example_dict.values()
['three', 'one', 'two'] # returns a list of all the values in our dictionary
The copy method

To copy a dictionary into another dictionary this can be done with the copy method

>>>example_dict1 = example_dict.copy{}
>>>print example_dict1
{'trois': 'three', 'une': 'one', 'deux': 'two'} # a new dictionary

This method is useful because if you try to copy a dictionary by using the equality operator,
You’re just referencing that dictionary and any changes made on that dictionary will also be made
To the new one.

And if we wanted to know if a key existed in our dictionary that’s also super easy

>>>”une” in example_dict
True  # “Une” exists in oor dictionary
>>>”cinq” in example_dict
False  # ”cinq” is not in our dictionary

This can also be done with the has_key method

>>>example_dict.has_key(“une”)
True
>>>example_dict.has_key(“cinq”)
False

Since dictionaries are a collection of items they can iterated upon, lets look at some ways to iterate over dictionaries.
Say we wanted to iterate only over all the keys, values or items python provides some built in methods for these.

>>>keys = example_dict.iterkeys() #The iterkeys method will return an iterator over the dictionary’s key
>>>for key in keys:
       print key
trois
une
deux
#Thats all the keys in our dictionary
>>>values = example_dict.itervalues() #Itervalues returns an iterator over our dictionary’s values
>>>for value in values:
       print value
three
one
two
#all the values in our dictionary
>>>items  = example_dict.iteritems() #iteritems return an iterator over our dictionary’s (key, value) pairs
>>> for k, v in items:
        print k, "-->", v
trois --> three
une --> one
deux --> two
#our whole collection of key and values

Another cool feature of dictionaries is the nice way they can be use for string formatting

>>> s = "After %(une)s comes %(deux)s then %(trois)s" %example_dict   # %s for string 
>>> print s
After one comes two then three # our output shows the corresponding values

Finally lets look at how to change and remove items in our dictionary

>>>example_dict[“une”] =1
>>>example_dict[“deux”] = 2
>>>example_dict[“trois”] = 3
>>>print example_dict
{'trois': 3, 'une': 1, 'deux': 2} # here we’ve changed the values of our keys

To delete items form our dictionary we’ll use the pop method which takes as argument the key of the item we would like to delete

>>>example_dict.pop("une")
1  # 1 is the value of “une”

Lets verify that it has been removed

>>>print example_dict
{'trois': 3, 'deux': 2}  # the key “une” and its value no longer exist in our dictionary

We could also use the del operator to perform deletion

>>>del example_dict[“deux”] 
>>>print example_dict
{'trois': 3}  # the key “deux” and its value has been deleted from  our dictionary.

There is still a lot that can be done with python dictionaries this is just a playful introduction.
Happy Hacking.

Discover and read more posts from Kelvin Paschal
get started