Python dictionary

In the Previous article, we talked about Python List. Here I will tell you more about the Python dictionary.

Dictionaries are the key-value stores in Python. They enable a fast access to elements because of the hash-table like implementation and that the keys have to be unique. Keys and values are separated by a colon (:) and the whole dictionary is defined between curly braces ({}).

Creating dictionaries and accessing elements

An empty dictionary is created with the opening and closing curly braces:

>>> d = {}
>>> type(d)
<class 'dict'>

To have a dictionary with values we have to add key-value pairs between those curly braces. Keys have the same restrictions as set-elements: they have to be hashable so no lists, dictionaries, sets are allowed, only immutable values like numbers, strings, boolean values, tuples, and frozensets.

>>> d = {'name':'Gabor', 'age':31}
>>> d
{'name': 'Gabor', 'age': 31}

Naturally, you can use a dictionary variable just like a real dictionary. For example, you could create an English-German dictionary to “translate” some words.

>>> en_de = {'eggs':'Eier', 'sausage':'Würstchen','bacon':'Schinken', 'spam':'Spam'}
>>> en_de
{'bacon': 'Schinken', 'sausage': 'Würstchen', 'eggs': 'Eier', 'spam': 'Spam'}
>>> en_de['eggs']
'Eier'
>>> en_de['baked beans']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'baked beans'
>>> en_de.get('baked beans','unknown')
'unknown'

As you can see above accessing elements can be done through their keys (like en_de[‘eggs’] in the example) however if a key is not present in python dictionary you will get a KeyError.

Naturally, you can avoid the KeyError with the usage of the get method which accepts an optional default value. If the optional default value is not provided then None is returned if the key is not present in the dictionary:

>>> bb = en_de.get('baked beans')
>>> print(bb)
None

If you have two lists then you might want to merge them into a list of pairs (key-value pairs eventually). This you can do with the zip function. After this, you can convert this zipped list to a dictionary where the first element of every pair will be the keys and the second elements of the pairs will be the value.

>>> food = ['eggs', 'sausage','bacon','spam']
>>> preferences = ['yes','no','yes','no']
>>> food_preferences = dict(zip(food, preferences))
>>> food_preferences
{'bacon': 'yes', 'sausage': 'no', 'eggs': 'yes', 'spam': 'no'}

As you can see above this is an exquisite and Pythonic way to convert two lists into a dictionary.

Adding and removing elements

Naturally, you can add and remove elements to/from a dictionary. The methods are quite the same as we learned with lists but let’s see them with examples.

>>> d = {'eggs':2}
>>>
>>> d
{'eggs': 2}
>>> d['bacon'] = 1
>>> d
{'bacon': 1, 'eggs': 2}
>>> d.update({'spam':0})
>>> d
{'bacon': 1, 'eggs': 2, 'spam': 0}
>>> d.update([('spam',1)])
>>> d
{'bacon': 1, 'eggs': 2, 'spam': 1}

The update function takes a dictionary as a parameter or a list of key-value pairs. And tuples are ideal candidates for those key-value pairs.

To remove elements from a dictionary, you can use the well-known del statement and provide a key along with the name of the dictionary. Naturally, if the key is not present in the dictionary, you will get a KeyError.

The pop function removes the element with the given key and returns the value associated with this key. If the key is not present, you will get a KeyError. To solve this problem, you can pass along a default value with the pop function which is returned when the given key is not in the dictionary.

The popitem function removes one element from the dictionary and returns the removed (key, value) pair as a tuple. Here you cannot know which element is returned. If the dictionary is empty, then you will get a KeyError.

>>> food_preferences = {'bacon': 'yes', 'sausage': 'no', 'eggs': 'yes', 'spam': 'no'}
>>> del food_preferences['spam']
>>> food_preferences
{'bacon': 'yes', 'sausage': 'no', 'eggs': 'yes'}
>>> del food_preferences['spam']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'spam'
>>> food_preferences.pop('spam')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'spam'
>>> food_preferences.pop('eggs')
'yes'
>>> food_preferences
{'bacon': 'yes', 'sausage': 'no'}
>>> food_preferences.pop('spam','no')
'no'
>>> food_preferences.popitem()
('bacon', 'yes')
>>> food_preferences
{'sausage': 'no'}
>>> food_preferences.clear()
>>> food_preferences
{}
>>> food_preferences.popitem()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'popitem(): dictionary is empty'

Is a specific key in the dictionary?

Sometimes you just want to avoid the usage of the get function because you do not need any default value if the requested key is not in the dictionary. In this case, you can use them in a statement with the key on the dictionary.

>>> d = {'eggs': 1, 'sausage': 2, 'bacon': 1}
>>> d
{'bacon': 1, 'sausage': 2, 'eggs': 1}
>>> 'spam' in d
False
>>> 'eggs' in d
True
>>> 'Eggs' in d
False

As you can see in the example above the keys are key-sensitive. This means a dictionary can contain a key ‘spam’, ‘Spam’ and ‘SPAM’ and all them would refer to different entries.

Keys and values of the dictionary

Sometimes you only need the information which keys are present in the dictionary, or you want to know which values are in there — or you need the values only in that case when the key exists.

In this case, you can use the keys or values method of a dictionary. As you might think they give you back a set-like object of keys or values in the dictionary. Let’s take a look at an example.

>>> d = {'first_name': 'Gabor', 'age':31, 'twitter':'@GHajba'}
>>> d
{'first_name': 'Gabor', 'age': 31, 'twitter': '@GHajba'}
>>> d.keys()
dict_keys(['first_name', 'age', 'twitter'])
>>> d.values()
dict_values(['Gabor', 31, '@GHajba'])

These set-like objects are not indexable, but you can use them later in loops for example. The dict_values object is useful when you want to see if a value is in the dictionary.

>>> d = {'first_name': 'Gabor', 'age':31, 'twitter':'@GHajba'}
>>> "Gabor" in d.values()
True
>>> "twitter" in d.values()
False

Naturally, you can use the list function and convert these dictionary set-like objects to lists (or with the set keyword to sets or with the tuple function you can create a tuple containing all the items — I hope you get the hang of it).

>>> list(d.keys())
['first_name', 'age', 'twitter']
>>> tuple(d.values())
('Gabor', 31, '@GHajba')
>>> set(d.items())
{('first_name', 'Gabor'), ('age', 31), ('twitter', '@GHajba')}

As you can see in the example above using the items function of the dictionary you get back a list of pairs where the first element is the key, the second element is the value.

 

References

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.