Python Dictionaries
A dictionary is a set of unordered key, value pairs. In a dictionary, the keys must be unique and they are stored in an unordered manner.
In this tutorial you will learn the basics of how to use the Python dictionary.
By the end of the tutorial you will be able to - Create Dictionaries - Get values in a Dictionary - Add and delete elements in a Dictionary - To and For Loops in a Dictionary
Creating a Dictionary
Let’s try to build a profile of three people using dictionaries. To do that you separate the key-value pairs by a colon(“:”). The keys would need to be of an immutable type, i.e., data-types for which the keys cannot be changed at runtime such as int, string, tuple, etc. The values can be of any type. Individual pairs will be separated by a comma(“,”) and the whole thing will be enclosed in curly braces({...}
).
For example, you can have the fields “city”, “name,” and “food” for keys in a dictionary and assign the key,value pairs to the dictionary variable person1_information.
>>> person_information = {'city': 'San Francisco', 'name': 'Sam', "food": "shrimps"}
>>> type(person1_information)
<class 'dict'>
>>> print(person1_information)
{'city': 'San Francisco', 'name': 'Sam', 'food': 'shrimps'}
Get the values in a Dictionary
To get the values of a dictionary from the keys, you can directly reference the keys. To do this, you enclose the key in brackets [...]
after writing the variable name of the dictionary.
So, in the following example, a dictionary is initialized with keys “city”, “name,” and “food” and you can retrieve the value corresponding to the key “city.”
>>> create a dictionary person1_information
>>> person1_information = {'city': 'San Francisco', 'name': 'Sam', "food": "shrimps"}
>>> print the dictionary
>>> print(person1_information["city"])
San Francisco
You can also use the get method to retrieve the values in a dict. The only difference is that in the get method, you can set a default value. In direct referencing, if the key is not present, the interpreter throws KeyError.
>>> # create a small dictionary
>>> alphabets = {1: ‘a’}
>>> # get the value with key 1
>>> print(alphabets.get(1))
'a'
>>> # get the value with key 2. Pass “default” as default. Since key 2 does not exist, you get “default” as the return value.
>>> print(alphabets.get(2, "default"))
'default'
>>> # get the value with key 2 through direct referencing
>>> print(alphabets[2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 2
Looping over dictionary
Say, you got a dictionary, and you want to print the keys and values in it. Note that the key-words for
and in
are used which are used when you try to loop over something. To learn more about looping please look into tutorial on looping.
>>> person1_information = {'city': 'San Francisco', 'name': 'Sam', "food": "shrimps"}
>>> for k, v in person1_information.items():
... print("key is: %s" % k)
... print("value is: %s" % v)
... print("###########################")
...
key is: food
value is: shrimps
###########################
key is: city
value is: San Francisco
###########################
key is: name
value is: Sam
###########################
Add elements to a dictionary
You can add elements by updating the dictionary with a new key and then assigning the value to a new key.
>>> # initialize an empty dictionary
>>> person1_information = {}
>>> # add the key, value information with key “city”
>>> person1_information["city"] = "San Francisco"
>>> # print the present person1_information
>>> print(person1_information)
{'city': 'San Francisco'}
>>> # add another key, value information with key “name”
>>> person1_information["name"] = "Sam"
>>> # print the present dictionary
>>> print(person1_information)
{'city': 'San Francisco', 'name': 'Sam'}
>>> # add another key, value information with key “food”
>>> person1_information["food"] = "shrimps"
>>> # print the present dictionary
>>> print(person1_information)
{'city': 'San Francisco', 'name': 'Sam', 'food': 'shrimps'}
Or you can combine two dictionaries to get a larger dictionary using the update method.
>>> # create a small dictionary
>>> person1_information = {'city': 'San Francisco'}
>>> # print it and check the present elements in the dictionary
>>> print(person1_information)
{'city': 'San Francisco'}
>>> # have a different dictionary
>>> remaining_information = {'name': 'Sam', "food": "shrimps"}
>>> # add the second dictionary remaining_information to personal1_information using the update method
>>> person1_information.update(remaining_information)
>>> # print the current dictionary
>>> print(person1_information)
{'city': 'San Francisco', 'name': 'Sam', 'food': 'shrimps'}
Delete elements of a dictionary
To delete a key, value pair in a dictionary, you can use the del
method.
>>> # initialise a dictionary with the keys “city”, “name”, “food”
>>> person1_information = {'city': 'San Francisco', 'name': 'Sam', "food": "shrimps"}
>>> # delete the key, value pair with the key “food”
>>> del person1_information["food"]
>>> # print the present personal1_information. Note that the key, value pair “food”: “shrimps” is not there anymore.
>>> print(person1_information)
{'city': 'San Francisco', 'name': 'Sam'}
A disadvantage is that it gives KeyError if you try to delete a nonexistent key.
>>> # initialise a dictionary with the keys “city”, “name”, “food”
>>> person1_information = {'city': 'San Francisco', 'name': 'Sam', "food": "shrimps"}
>>> # deleting a non existent key gives key error.
>>> del person1_information["non_existent_key"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'non_existent_key'
So, instead of the del
statement you can use the pop
method. This method takes in the key as the parameter. As a second argument, you can pass the default value if the key is not present.
>>> # initialise a dictionary with key, value pairs
>>> person1_information = {'city': 'San Francisco', 'name': 'Sam', "food": "shrimps"}
>>> # remove a key, value pair with key “food” and default value None
>>> print(person1_information.pop("food", None))
'Shrimps'
>>> # print the updated dictionary. Note that the key “food” is not present anymore
>>> print(person1_information)
{'city': 'San Francisco', 'name': 'Sam'}
>>> # try to delete a nonexistent key. This will return None as None is given as the default value.
>>> print(person1_information.pop("food", None))
None
More facts about the Python dictionary
You can test the presence of a key using the has_key
method.
>>> alphabets = {1: ‘a’}
>>> alphabets.has_key(1)
True
>>> alphabets.has_key(2)
False
A dictionary in Python doesn't preserve the order. Hence, we get the following:
>>> call = {'sachin': 4098, 'guido': 4139}
>>> call["snape"] = 7663
>>> call
{'snape': 7663, 'sachin': 4098, 'guido': 4139}
You see that even though "snape" was given later, it appeared at the top.