Python Dictionary
Python dictionary is an unordered collection of key-value pairs. The use of key-value pairs in the dictionary makes accessing the value more optimized if we know the key.
Creation of Python Dictionary :
In python, the dictionary can be created by placing comma-separated key-value pairs in curly braces { }. Or we can use the dict() method for creating the dictionary from the supported iterable object.
The values of the dictionary can be of any data type and can repeat. But the keys of the dictionary should be immutable like tuples, strings, and numbers. Moreover, keys should be Unique.
Note: Dictionary keys are case sensitive, the same name in different cases is treated as different keys. Like TUF and tuf are treated as different keys.
Code :
Python Code
# creating an empty dictionary
dict1 = {}
print("Empty Dictionary")
print(dict1)
# creating a dictionary with comma-seperated key value pairs
# dictionary with keys of different types
print("\nDictionary with different immutable keys")
dict2 = {"tuf": "striver", "Numbers": [1, 2, 3, 4, 5], (1, 4, 9, 16, 25): "squares"}
print(dict2)
# creating dictionary with dict() method
print("\nDictionary created using dict() method")
dict3 = dict([("Bharat", "India"), ("Raj", "vikramaditya")])
print(dict3)
# creating dictionary with case sensitive Keys
# keys lionei, Lionei are different
print("\nDictionary with case sensitive keys")
dict4 = {"lionei": "messi", "Lionei": "Messi"}
print(dict4)
# creating dictionary with repeating values
print("\nDictionary with repeating value")
dict5 = {"integers": (1, 2, 3, 4, 5), "real numbers": (1, 2, 3, 4, 5)}
print(dict5)
# Dictionary with Immutable keys,throws error
# Here the keys are of type list and set which are mutable hence, raises error.
dict6 = {["kohli", "roht", "Dhoni"]: "India", {1, 2, 3, 4}: "set"}
print(dict6)
Output:
Empty Dictionary
{}
Dictonary with different immutable keys
{‘tuf’: ‘striver’, ‘Numbers’: [1, 2, 3, 4, 5], (1, 4, 9, 16, 25): ‘squares’}
Dictonary created using dict() method
{‘Bharat’: ‘India’, ‘Raj’: ‘vikramaditya’}
Dictonary with case sensitive keys
{‘lionei’: ‘messi’, ‘Lionei’: ‘Messi’}
Dictonary with repeating value
{‘integers’: (1, 2, 3, 4, 5), ‘real numbers’: (1, 2, 3, 4, 5)}
Traceback (most recent call last):
File “c:\Users\angaj\Desktop\tuf codes\python_data_types.py”, line 26, in <module>
dict6 = {[‘kohli’, ‘roht’, ‘Dhoni’]: ‘India’, {1, 2, 3, 4}: ‘set’}
TypeError: unhashable type: ‘list’
Nested Dictionaries :
As the values of a dictionary can be any data type, so the value can be also a dictionary. In that scenario, the dictionary is said to be a nested dictionary.
Code :
Python Code
# creation of Nested Dictonary
dict = {1: 'tuf',
2: 'striver',
3: {'squares': [1, 4, 9],
'cubes': [1, 8, 27]}
}
print(dict)
output:
{1: ‘tuf’, 2: ‘striver’, 3: {‘squares’: [1, 4, 9], ‘cubes’: [1, 8, 27]}}
Accessing Elements from Dictionary :
As the dictionaries are unordered collections they cannot be accessed by indexing like in other sequence data types. Values are accessed using the key inside the square brackets [ ] or with get() method.
If the key is not found in the dictionary, then square brackets notation throws a KeyError While the get() methods don’t raise any error. So it is better to use the get() method for accessing the value of the corresponding key.
Code :
Python Code
dict = {1: 'tuf',
2: 'striver',
3: {'squares': [1, 4, 9],
'cubes': [1, 8, 27]}
}
# accesing value corresponding to key 1 using square bracket.
print(dict[1])
# accesing value corresponding to key 2 using get() method
print(dict.get(2))
# accesing nested dictonary value
print(dict[3]['squares'])
# accessing key which is not present in dictonary using get() method.
# as key is not present,get() returns None and do not raise any error
print(dict.get(4))
# accesing key which is not present using [ ],raises KeyError
print(dict[4])
Output:
tuf
striver
[1, 4, 9]
None
Traceback (most recent call last):
File “c:\Users\angaj\Desktop\tuf codes\python_data_types.py”, line 20, in <module>
print(dict[4])
KeyError: 4
Modifying Dictionary Elements :
As we all know that the Dictionary is mutable, New (key: value) pairs can be added, and existing the value of the keys can be changed. New value can be added dictionary using the assignment operator. The value of the existing key can be updated using the update() method.
Syntax :
dictonaryName[key] = value
Note: If the key is already present then the value of the key is updated, else new (key: value) pair is added to the dictionary.
Code :
Python Code
dict = {1: 'tuf',
2: 'striver',
3: {'squares': [1, 4, 9],
'cubes': [1, 8, 27]}
}
# updating the value of key 1
dict[1] = 'takeuforward'
print(dict)
# adding the new (key:value) pair to dictonary
dict[4] = 'India'
print(dict)
Output:
{1: ‘takeuforward’, 2: ‘striver’, 3: {‘squares’: [1, 4, 9], ‘cubes’: [1, 8, 27]}}
{1: ‘takeuforward’, 2: ‘striver’, 3: {‘squares’: [1, 4, 9], ‘cubes’: [1, 8, 27]}, 4: ‘India’}
Removing Elements From Dictionary :
A particular (key: value) pair in the dictionary can be removed by using the pop() method. The pop method takes the key as a parameter and removes the corresponding (key: value) pair from the dictionary. the pop() method returns the value of the deleted key.
An arbitrary (key: value) pair can be removed using the popitem(), it returns the removed (key: value) pair. clear() method can be used to remove all the (key: value) pairs in the dictionary. Keyword del can be used to delete the dictionary itself.
Code :
Python Code
d = {1: 'tuf',
2: 'striver',
'squares': [1, 4, 9],
'cubes': [1, 8, 27]
}
# removing the (1:tuf) from the dictonary using pop() method.
print(d.pop(1)) # output the value of key 1 i.e tuf
print(d)
# removing an arbitary (key:value) pair from dictonary using popitem() method.
print('\n', d.popitem()) # outputs the removed (key:value)
print(d)
# removing all items from dictonary
d.clear()
print('\n', d)
# deleting the dictonary
del d
print(d)
Output:
tuf
{2: ‘striver’, ‘squares’: [1, 4, 9], ‘cubes’: [1, 8, 27]}
(‘cubes’, [1, 8, 27])
{2: ‘striver’, ‘squares’: [1, 4, 9]}
{}
Traceback (most recent call last):
File “c:\Users\angaj\Desktop\tuf codes\python_data_types.py”, line 17, in <module>
print(d)
NameError: name ‘d’ is not defined. Did you mean: ‘id’?
Python Dictionary Methods :
Python provides some methods to deal with dictionaries. Below are the methods of the dictionary class.
Method | Description |
clear() | Removes all the items from the dictionary |
copy() | Returns a copy of the dictionary |
items() | Returns a new object of the dictionary items in (key: value) format |
keys() | Returns a new object of dictionary keys |
popitem() | Removes an arbitrary (key: value) pair and returns it. Raises KeyError if the dictionary is empty. |
values() | Returns a new object of dictionary’s values. |
get() | Returns the value of the provided key |
update() | Updates dictionary with provided (key: value) pairs. |
Let’s look at these methods one by one
copy()
Code:
Python Code
d = {1: 'tuf',
2: 'striver',
'squares': [1, 4, 9],
'cubes': [1, 8, 27]
}
copy_of_d = d.copy()
print(copy_of_d)
Output:
{1: ‘tuf’, 2: ‘striver’, ‘squares’: [1, 4, 9], ‘cubes’: [1, 8, 27]}
items(), keys(), values()
Python Code
d = {1: 'tuf',
2: 'striver',
'squares': [1, 4, 9],
'cubes': [1, 8, 27]
}
# items() method.
print("The items of the dictonary are : ")
print(d.items())
# keys() method
print('\n All the keys of the dictionary are : ')
print(d.keys())
# values() method
print('\n All the values of the dictonary are : ')
print(d.values())
Output:
The items of the dictonary are :
dict_items[1, ‘tuf’), 2, ‘striver’), ‘squares’, [1, 4, 9]), ‘cubes’, [1, 8, 27])])
All the keys of the dictionary are :
dict_keys[1, 2, ‘squares’, ‘cubes’])
All the values of the dictonary are :
dict_values[‘tuf’, ‘striver’, [1, 4, 9], [1, 8, 27]])
update()
update() method updates the elements of dictionary from another dictionary object or from a iterable of (key:value) pairs.
Code:
Python Code
d = {1: 'tuf',
2: 'striver'
}
# updating from another dictonary
# key 1 is present in dictonary d, so it's value get updated to takeuforward.
# key factorials is not present in d,so it is added to dictonary d
d.update({1: 'takeuforward', 'factorials': [1, 2, 6, 24, 120]})
print(d)
# updating from iterable (key:value) pairs
# The value of key 2 gets updated to Raj Vikramaditya and key digits is added to
#dictonary
d.update([(2, 'Raj Vikramaditya'), ('digits', [0, 1, 2, 3, 4])])
print(d)
Output:
{1: ‘takeuforward’, 2: ‘striver’, ‘factorials’: [1, 2, 6, 24, 120]}
{1: ‘takeuforward’, 2: ‘Raj Vikramaditya’, ‘factorials’: [1, 2, 6, 24, 120], ‘digits’: [0, 1, 2, 3, 4]}
Special thanks to SaiSri Angajala for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article. If you want to suggest any improvement/correction in this article please mail us at [email protected]