- 0shares
- Facebook0
- Twitter0
- Google+0
- Pinterest0
- LinkedIn0
Python Dictionary
In this section we will learn about the dictionary data type in Python. We will demonstrate how the Python dictionaries are created in Python and how remove or add items into the Python dictionary. We will also discuss a number of Python methods that can be used with Python dictionary.
A Python dictionary can be considered as the unordered collection of the items. A dictionary consists of a key and a value as pair. Therefore, this pair can be written as:
key: value
The Python dictionaries are used to retrieve the values when the key is known.
How to create a dictionary?
A dictionary in Python can be created by placing the items inside the curly braces and are separated by a comma. An item in the dictionary is a pair that consists of a key and a value written as: key: value.
The values in the dictionary can be of different data types and can also be repeated. The keys in the dictionary are immutable and should also be unique. There is a built in function by using which we can create a dictionary. This function is named as dict ().
Consider the following example in which we have initialized Python dictionary:
CODE
>>> myDic = {}
>>> myDic = {1:’Python’, 2:’Programming’}
>>> myDic = {‘Python’: ‘Programming’, 1: [1,2,3]}
In the above lines of code, the first line initializes an empty dictionary; the second line initializes a dictionary that has keys and their corresponding values. The third line initializes the dictionary with mixed keys.
Now consider the following line of code in which we have defined a dictionary using the built in function dict ():
CODE
>>> myDict = dict ({1: ‘Python’, 2: ‘Programming’})
>>> myDict = dict ([(1, ‘Python’), (2, ‘Programming’)])
In the above lines of code, the first line simply declares a dictionary that has two keys and their corresponding values using the built in dict () function. In the second line the dictionary is initialized with item as a pair.
How to access elements from a dictionary?
In other sequences like list, tuple etc we used index to access the elements of the sequence but to access the elements of the dictionary the keys of the dictionaries are used. We can use the keys of the dictionaries in two ways that is either inside the square brackets or by using them in the built in method that is get () method.
When we use the key in the get () method if the key is not found in the dictionary then the ‘get ()’ method returns none instead of generating the key error.
Consider the following example in which declared a dictionary and access its element by the above described ways:
CODE
>>> myDic = {‘name’ : ‘Stuart’, ‘age’ :26}
>>> print (myDic [‘name’])
>>> print (myDic. get (‘age’))
OUTPUT
Stuart
26
How to change or add elements in the dictionary?
In Python a dictionary is mutable that is we can add or change elements of the dictionary. The value of the existing elements can be changed by using the assignment operator. If the key exists already in the dictionary then value will be updated. If there was no key present then a new pair will be added into the dictionary.
Consider the following example in which a dictionary is initialized and then we added an item in the dictionary:
CODE
>>> myDic = {‘name’: ‘Stuart’, ‘age’ : 26}
>>> myDic [‘age’] = 24
>>> print (myDic)
>>> myDic [‘address’] = ‘Street1’
>>> print (myDic)
OUTPUT
{‘age’: 24, ‘name’: ‘Stuart’}
{‘age’: 24, ‘name’: ‘Stuart’, ‘address’: ‘Street1’}
In the above example a new pair with a value and a key is inserted to the dictionary.
How to delete or remove elements from the dictionary?
In Python the elements can be removed by using the built in function pop (). The item with the key is deleted from the dictionary when the pop () function is used and it return the value.
There is another function that can be used to remove and return the arbitrary item from a dictionary, this method is called popitem (). If the user wants to remove all the items from the dictionary then he can use the clear () function, the dictionary will be cleared. To delete the entire dictionary we use the del keyword.
Consider the following example:
CODE
>>> adds = {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
>>> print (adds. pop (4))
>>> print (adds)
>>> print (adds. popitem ())
>>> print (adds)
>>> del adds [5]
>>> print (adds)
>>> adds. clear ()
>>> print (adds)
>>> del adds
>>> print (adds)
OUTPUT
8
{1: 2, 2: 4, 3: 6, 5: 10}
(1, 2)
{2: 4, 3: 6, 5: 10}
{2: 4, 3: 6}
{}
Traceback (most recent call last):
File “<pyshell#12>”, line 1, in <module>
print (adds)
NameError: name ‘adds’ is not defined
In the above example a dictionary named ‘adds’ is declared and. In the first print statement the pop () function is used to pop an item of the dictionary. In third print statement the popitem () function is used to remove and return an arbitrary item from the dictionary. The del keyword is used to delete the value corresponding to the key 5. The clear () function is used to remove all the items from the dictionary. The del keyword is again used to delete the entire dictionary from the memory.
Python dictionary Methods
Consider the following table in which the dictionary methods in Python are described:
Method | Description |
clear () | This method is used to remove all the elements or items from the dictionary. |
copy () | This method is used to return a copy of the dictionary (shallow copy). |
fromkeys (seq[, v]) | This method is used to return a new dictionary from the sequence and equals it to v. |
get (key[, d]) | This method is used to return the value of the key. |
items () | This method is used to return a new view of the items of dictionary. |
keys () | This method is used to return a new view of the key of the dictionary. |
pop (key[,d]) | This method is used to remove the item from the dictionary along with its key and returns the value d. If the value of d is not provided and the key is not found in dictionary then key error will be generated. |
popitem () | This method is used to remove and then return the arbitrary item. |
setdefault (key[, d]) | This method is used to return the value of the key if the key exists in the dictionary. |
update ([other]) | This method is used to update the dictionary with items from other dictionary. |
values () | This method is used to return the new view of key of dictionary. |
Python Dictionary Comprehension
A new dictionary can be created from an iterable in Python by using the most elegant way that is by using the dictionary comprehension. The dictionary comprehension consists of the pair of key and value that is followed by the ‘for’ statement inside curly braces.
Consider the following example in which a dictionary is created and in each item 2 is added:
CODE
>>> adds = {x: x+2 for x in range (5)}
>>> print (adds)
OUTPUT
{0: 2, 1: 3, 2: 4, 3: 5, 4: 6}
We can also write the above code as the following lines of code:
CODE
>>> adds = {}
>>> for x in range (5):
adds [x]=x+2
>>> print (adds)
OUTPUT
{0: 2, 1: 3, 2: 4, 3: 5, 4: 6}
A dictionary comprehension can contain a ‘for’ statement or the ‘if’ statement. The “if statement” is used to filter values for the new dictionary.
Consider the following example in which we have used the “if statement” with for statement for dictionary comprehension to print only the even numbers:
CODE
>>> even_adds = {x: x+2 for x in range (10) if x%2==0}
>>> print (even_adds)
OUTPUT
{0: 2, 8: 10, 2: 4, 4: 6, 6: 8}
Other Dictionary Options
Dictionary Membership Test
In Python we can test a key in the dictionary by using the keyword in. By testing a key in the dictionary we mean that if the key exists in the dictionary or not.
Consider the following example in which we have declared a dictionary and checked if the key exists in the declared dictionary or not by using the in keyword Python:
CODE
>>> adds = {0: 2, 1: 3, 2: 4, 3: 5, 4: 6}
>>> print (1 in adds)
>>> print (7 in adds)
>>> print (7 not in adds)
OUTPUT
True
False
True
It can be seen that the interpreter returned True when the key is in the dictionary and returned false when the key is not in the dictionary when using the in keyword. When we used the not in keyword the interpreter returned true because 7 is not in the dictionary.
Iterating through a Dictionary
In Python we can iterate through each key of the dictionary by using the ‘for statement’. Consider the following example in which we have used the ‘for statement’ to iterate through the keys of the dictionary:
CODE
>>> adds = {0: 2, 1: 3, 2: 4, 3: 5, 4: 6}
>>> for x in adds:
print (adds[x])
OUTPUT
2
3
4
5
6
In the above example for loop is used to iterate through the keys of the dictionary. The counter variable ‘x’ iterates through the each key of the dictionary and then this variable is printed using the print statement and all the values corresponding to keys of the dictionary are printed because x iterated through the keys of the dictionary.
Built in Functions with dictionary
The commonly used built in functions for Python dictionary may include all (), len (), any (), etc. Consider the following table in which various built in functions for Python dictionary are described:
Function | Description |
all () | This function is used to return a true if all the keys in the dictionary are true and if the dictionary is empty. |
any () | This function is used to return a true if any of the keys in the dictionary are true and returns a false if the dictionary is empty. |
len () | This function is used to return the length of the dictionary or the number of items in the set. |
cmp () | This function is used to compare all the items of one dictionary from the items of other dictionary. |
sorted () | This function is used to a new sorted list of keys that are the part of the dictionary. The sorted () function does not sort the dictionary itself but it returns the already sorted dictionary. |
Consider the following example in which we have used the len () function to find the length of the dictionary and the sorted () function to return the sorted dictionary:
CODE
>>> adds = {0: 2, 1: 3, 2: 4, 3: 5, 4: 6}
>>> print (len (adds))
>>> print (sorted (adds))
OUTPUT
5
[0, 1, 2, 3, 4]