Dictionaries in python are used to store data in key-value pairs. Values in a dictionary are changeable via methods that will be discussed later on in this article. The syntax of a dictionary is as follows:
this_dict = {
'fname': 'John',
'lname': 'Doe',
'gender': 'male',
'age': 23,
'Citizen by birth': True
}
print(this_dict)
A dictionary accepts various data types like integers, strings, booleans, and lists. Items stored in a dictionary get the type of 'dict'. It is important to note that dictionaries in Python do not accept duplicates. Dictionaries in python are ordered, which means that the items have a defined order, which does not change. This also implies that one can access the items by an index. That is:
this_dict = {
'fname': 'John',
'lname': 'Doe',
'gender': 'male',
'age': 23,
'Citizen by birth': True
}
print(this_dict['fname'])
Through the code snippet above, we can access the value of the key 'fname', which is 'John'. When duplicate items are stored in dict, the latter gets the priority and the earlier stated value gets ignored.
this_dict = {
'fname': 'John',
'fname': 'Doe',
'gender': 'male',
'age': 23,
'Citizen by birth': True
}
print(this_dict['fname'])
In the above code, the first value 'fname', gets ignored, while the second gets displayed when the code is run. We also have another way of making a dictionary by use of the dict() constructor, for instance:
my_dict = dict(name='John', age=23, gender= 'male')
print(my_dict)
Accessing items in a dictionary
You can access the value of an item stored in a dictionary by calling its key within square brackets:
this_dict = { 'fname': 'John', 'lname': 'Doe', 'gender': 'male', 'age': 23, 'Citizen by birth': True } print(this_dict['fname'])
by use of the .get() method
this_dict = { 'fname': 'John', 'lname': 'Doe', 'gender': 'male', 'age': 23, 'Citizen by birth': True } x = this_dict.get('fname') print(x)
- By using the .keys() method, it returns a list of all keys in the dictionary.
- On the other hand, .values() returns a list of all values in the dictionary.
- .items() returns each item as tuples in a list. Being a tuple in a list means that changes can still be done to the dictionary, this is because unlike in a tuple, changes can be made to a list.
note
To check whether a particular key exists in a dictionary, we use the in keyword. For instance,
this_dict = { 'fname': 'John', 'lname': 'Doe', 'gender': 'male', 'age': 23, 'Citizen by birth': True } if 'fname' in this_dict: print('key fname present')
Changing items in a Python dictionary
There are two ways to change items in a dictionary in Python: - You can change the value of a specific item by referring to its key name, that is:
this_dict = {
'fname': 'John',
'lname': 'Doe',
'gender': 'male',
'age': 23,
'Citizen by birth': True
}
this_dict['fname'] = 'Jane'
print(this_dict)
This changes the value of 'fname' from 'John' to 'Jane'.
- We can also use the .update() method, which takes in the key: value as arguments. An example of the method in use is:
this_dict = {
'fname': 'John',
'lname': 'Doe',
'gender': 'male',
'age': 23,
'Citizen by birth': True
}
this_dict.update({'fname': 'Jane'})
print(this_dict)
The above code snippet updates the value of 'fname' from 'John' to 'Jane'.
The .update() keyword is also used to add new items to the dictionary. For instance:
this_dict = {
'fname': 'John',
'lname': 'Doe',
'gender': 'male',
'age': 23,
'Citizen by birth': True
}
this_dict.update({'mid-name': 'Smith'})
print(this_dict)
The above code adds the 'mid-name' key as the last item, and saves the value as 'Smith'.
Removing items from the Dictionary in Python
- .pop() method removes items with the specified key name.
- .popitem() removes the last inserted item
- The del keyword removes the item with the specified key name. The syntax of the del keyword is:
this_dict = {
'fname': 'John',
'lname': 'Doe',
'gender': 'male',
'age': 23,
'Citizen by birth': True
}
del this_dict['lname']
print(this_dict)
The above snippet deletes the 'lname' key item as well as its values. The del keyword can also be used to delete the dictionary completely such that when the dictionary is called it gives an error since it no longer exists.
this_dict = {
'fname': 'John',
'lname': 'Doe',
'gender': 'male',
'age': 23,
'Citizen by birth': True
}
del this_dict
print(this_dict)
Loop Dictionaries in Python
You can loop through a dictionary by use of a for loop. By default, the return values of a dictionary when looping are the keys of the dictionary. For example, to print all keys in the dictionary:
this_dict = {
'fname': 'John',
'lname': 'Doe',
'gender': 'male',
'age': 23,
'Citizen by birth': True
}
for x in this_dict:
print(x)
.values() method prints all the values in the dictionary. The syntax is:
this_dict = {
'fname': 'John',
'lname': 'Doe',
'gender': 'male',
'age': 23,
'Citizen by birth': True
}
for x in this_dict.values():
print(x)
.keys() method returns all the keys in the dictionary.
this_dict = {
'fname': 'John',
'lname': 'Doe',
'gender': 'male',
'age': 23,
'Citizen by birth': True
}
for x in this_dict.keys():
print(x)
You can also get both the key and value using .item() method. For instance:
this_dict = {
'fname': 'John',
'lname': 'Doe',
'gender': 'male',
'age': 23,
'Citizen by birth': True
}
for x, y in this_dict.items():
print(x, y)
Copying Dictionaries
You cannot copy a dictionary by simply calling dictionary2 = dictionary1. In fact, this is correct and dictionary2 gets the value of dictionary1. The problem arises because whenever a change is done to dictionary1, it gets carried forward by dioctionary2, which is not ideal, or not what we're looking for. We have to have a new independent dictionary2, which has similar key value items.
To copy a dictionary, we use the .copy() method. For example:
this_dict = {
'fname': 'John',
'lname': 'Doe',
'gender': 'male',
'age': 23,
'Citizen by birth': True
}
new_dict = this_dict.copy()
print(new_dict)
We can also use the dict() keyword, which takes in the original dictionary as the argument. For example:
this_dict = {
'fname': 'John',
'lname': 'Doe',
'gender': 'male',
'age': 23,
'Citizen by birth': True
}
new_dict = dict(this_dict)
print(new_dict)
Nested Dictionaries
The idea of nested loops is having a dictionary inside a dictionary. Nested dictionaries have two syntaxes, that is:
my_family = { 'child1': { 'name': 'Ess', 'age': 29, 'gender': 'female' }, 'child2': { 'name': 'Kev', 'age': 25, 'gender': 'male' }, 'child3': { 'name': 'eliud', 'age': 23, 'gender': 'male' } } print(my_family)
child1 = {
'name': 'Ess',
'gender': 'female',
'age': 29
}
child2 = {
'name': 'Kev',
'gender': 'male',
'age': 26
}
child3 = {
'name': 'eliud',
'gender': 'male',
'age': 23
}
my_family = {
'child1': child1,
'child2': child2,
'child3': child3
}
print(my_family)
As we've seen in the article dictionaries in python have a large scope, which I tried to cover. This article has led us to discover a new data type in python called dict. Thank you, I hope this article is of help to your coding journey.