What is a Dictionary in Python?
Python Dictionary or Dictionary in Python is a data-structure in Python that is also known as associative array. A python dictionary is used to store data values in key:value pair. Each item has a key and a corresponding value that is expressed as a pair (key: value). They are optimised to retrieve values when the key is known.
Are Python Dictionaries ordered?
In Python 3.6 and beyond, dictionaries are ordered data structures. It means that a Python dictionary keeps the order of the element in which it is added to the dictionary.
Are Python Dictionaries mutable?
Yes, dictionaries in Python are mutable and you can add, delete and update an item of a Python Dictionary.
Are Python Dictionaries hashable?
No, a dictionary in Python is not hashable and you can not use a dictionary as a key in another dictionary.
Can a dictionary has duplicate keys?
No, the keys in a dictionary are much like a set, which is a collection of hashable and unique objects. Because the objects need to be hashable, mutable objects can’t be used as dictionary keys.
How to create a Dictionary in Python ?
You can easily create a Python Dictionary or Dictionary in Python by enclosing comma-separated key-values pairs in curly brackets ({}), where the key and values are separated by a colon ‘:’.
a_dictionary = {
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}
A dictionary in Python can also be created by using the built-in function called dict().
a_dictionary = dict([(1, 'Saral'), (2, 'Gyaan')])
print(a_dictionary)
# Output
{1: 'Saral', 2: 'Gyaan'}
How to create an empty dictionary in Python?
If you want to create an empty dictionary in python, you can use the following code
a_dictionary = {}
b_dictionary = dict()
print(a_dictionary, type(a_dictionary))
print(b_dictionary, type(b_dictionary))
# Output
{} <class 'dict'>
{} <class 'dict'>
How to create a Dictionary in Python using Comprehension
Using Dictionary comprehension is an elegant way to create a dictionary in Python. It can be used like list comprehensions
all_squares = {i:i**2 for i in range(1,11)}
print(all_squares)
# Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
How to access an element from a Python Dictionary ?
Accessing element from a python dictionary is quite easy, instead of using indexes like Python Lists, dictionary use keys in square brackets :-
a_dictionary = {'name' : 'Saral', 'age' :33}
print(a_dictionary['name'])
print(a_dictionary['age'])
# Output
Saral
33
However, if we pass a key in the square brackets that is not present in the dictionary, it will through a key error.
print(a_dictionary['email'])
# Output
KeyError: 'email'
To overcome this KeyError, we can use get() method instead. If the key is not present, it will return None instead of throwing an error
a_dictionary = {'name' : 'Saral', 'age' :33}
print(a_dictionary.get('name'))
print(a_dictionary.get('age'))
print(a_dictionary.get('email'))
# Output
Saral
33
None
How to iterate through a dictionary in Python?
You can iterate through a Python Dictionary using either of the four following ways :
- Iterating through keys directly
- Iterating through .items()
- Iterating through .keys()
- Iterating through .values()
Iterating a Python Dictionary through keys directly
You can iterate through a Python Dictionary by directly using the keys:-
a_dictionary = {'name' : 'Saral', 'age' :33}
for key in a_dictionary:
print(key)
# Output
name
age
However, if you also want to get the values, you can use the following code:-
a_dictionary = {'name' : 'Saral', 'age' :33}
for key in a_dictionary:
print(key, a_dictionary[key])
# Output
name Saral
age 33
Iterating a Python Dictionary through .items()
You can also iterate through a Python Dictionary using .items()
a_dictionary = {'name' : 'Saral', 'age' :33}
for item in a_dictionary.items():
print(item)
# Output
('name', 'Saral')
('age', 33)
Here each item i.e. key and value pair is a tuple. You can check it as under:-
a_dictionary = {'name' : 'Saral', 'age' :33}
for item in a_dictionary.items():
print(type(item))
# Output
<class 'tuple'>
<class 'tuple'>
You can also unpack this tupe while iterating to get the key, value directly.
a_dictionary = {'name' : 'Saral', 'age' :33}
for key, value in a_dictionary.items():
print(f'{key} ---> {value}')
# Output
name ---> Saral
age ---> 33
Note- Here I have used Python f-strings, you can read more about them from here.
Iterating a Python Dictionary through .keys()
You can get the list of all the keys present in a Python Dictionary by using the following code:-
a_dictionary = {'name' : 'Saral', 'age' :33}
print(a_dictionary.keys())
# Output
dict_keys(['name', 'age'])
And then you can iterate through these like under:-
for key in a_dictionary.keys():
print(key)
print(f'{key} ---> {a_dictionary[key]}')
# Output
name
name ---> Saral
age
age ---> 33
Iterating a Python Dictionary through .values()
You can get the list of all the values present in a Python Dictionary by using the following code:-
a_dictionary = {'name' : 'Saral', 'age' :33}
print(a_dictionary.values())
# Output
dict_values(['Saral', 33])
And then you can iterate through these like under:-
for value in a_dictionary.values():
print(value)
# Output
Saral
33
How to change an element in Python Dictionary?
As discussed above, the python dictionaries are mutable, hence we can change an element of the python dictionary by using the following code:-
a_dictionary = {'name' : 'Saral', 'age' :33}
print(a_dictionary)
a_dictionary['age'] = 34
print(a_dictionary)
# Output
{'name': 'Saral', 'age': 33}
{'name': 'Saral', 'age': 34}
How to add a new element to Python Dictionary?
In the above example, we only changed the value of the key which was already present in the dictionary. However, we can also easily add a new key value pair to the dictionary. It is like appending a new element to the dictionary and the new key, value pair would be added at the last ( The dictionaries are ordered for Python 3.6 and beyond)
a_dictionary['email'] = 'admin@saralgyaan.com'
print(a_dictionary)
# Output
{'name': 'Saral', 'age': 34, 'email': 'admin@saralgyaan.com'}
How to add multiple new items/elements to a Python Dictionary?
We can also add a new element to a Python Dictionary by using .update() method. The advantage of using .update() method is that, we can use it to add multiple items to an existing dictionary in one go.
a_dictionary.update({'email': 'admin@saralgyaan.com'})
print(a_dictionary)
a_dictionary.update([('company', 'Saral Gyaan'), ('country', 'India')])
print(a_dictionary)
# Output
{'name': 'Saral', 'age': 34, 'email': 'admin@saralgyaan.com'}
{'name': 'Saral', 'age': 34, 'email': 'admin@saralgyaan.com', 'company': 'Saral Gyaan', 'country': 'India'}
How to insert a new element in a Python Dictionary at specific index?
There is no inbuilt method to insert a new element at a specific index of the Python Dictionary. However, there are few tricks using which you can insert the element at a specific index. If you want to insert an element at the begining of an existing dictionary, you can use th following code :-
a_dictionary = {'name' : 'Saral', 'age' :33}
a_dictionary = {'country' : 'India', **a_dictionary}
print(a_dictionary)
# Output
{'country': 'India', 'name': 'Saral', 'age': 33}
However, if you want to insert the item with index number, you can create a single line lambda function and then use it to insert the element
insert = lambda _dict, obj, pos: {k: v for k, v in (list(_dict.items())[:pos] + list(obj.items()) + list(_dict.items())[pos:])}
a_dictionary = insert(a_dictionary, {'email':'admin@saralgyaan.com'}, 1)
print(a_dictionary)
# Output
{'country': 'India', 'email': 'admin@saralgyaan.com', 'name': 'Saral', 'age': 33}
How to remove/delete an element from a Python Dictionary?
There are various ways using which you can delete an element from a Python Dictionary like using del keyword, pop(), popitem() method or clear() method.
Remove/delete an element using pop() method
You can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value.
a_dictionary = {'country': 'India', 'email': 'admin@saralgyaan.com', 'name': 'Saral', 'age': 33}
print(a_dictionary.pop('country'))
print(a_dictionary)
# Output
India
{'email': 'admin@saralgyaan.com', 'name': 'Saral', 'age': 33}
The first print statement is the value returned by the pop() method.
Remove/delete an element using popitem() method
popitem() method can be used to remove and return an arbitrary key value item from the dictionary. It removes the last item of the ordered dictionary.
a_dictionary = {'country': 'India', 'email': 'admin@saralgyaan.com', 'name': 'Saral', 'age': 33}
print(a_dictionary.popitem())
print(a_dictionary)
# Output
('age', 33)
{'country': 'India', 'email': 'admin@saralgyaan.com', 'name': 'Saral'}
Here, the first print statement returns the key:value pair.
Remove/delete an element using del keyword
Alternatively, you can use the del keyword with the key to remove the specific key:value pair. It won’t return the removed key or value.
a_dictionary = {'country': 'India', 'email': 'admin@saralgyaan.com', 'name': 'Saral', 'age': 33}
del a_dictionary['country']
print(a_dictionary)
# Output
{'email': 'admin@saralgyaan.com', 'name': 'Saral', 'age': 33}
You can also use the del keyword to delete the entire dictionary.
a_dictionary = {'country': 'India', 'email': 'admin@saralgyaan.com', 'name': 'Saral', 'age': 33}
del a_dictionary
print(a_dictionary)
# Output
Traceback (most recent call last):
File "D:\official\TRS\TRS\14.10\python work\upwork_1.py", line 65, in <module>
print(a_dictionary)
NameError: name 'a_dictionary' is not defined
Since, the del keyword deleted a_dictionary in the second line, we get an error if we try to print the dictionary after that.
Remove/delete all element using clear() method
You can also clear all the contents of the dictionary using clear() method. Unlike del, it only deletes the elements and not the dictionary itself and you would be left with an empty dictionary
a_dictionary = {'country': 'India', 'email': 'admin@saralgyaan.com', 'name': 'Saral', 'age': 33}
a_dictionary.clear()
print(a_dictionary)
# Output
{}
Python Dictionary Methods
Followings are the few important Python Dictionary Methods
Method | Description |
---|---|
clear() | Removes all items from the dictionary. |
copy() | Returns a shallow copy of the dictionary. |
fromkeys(seq[, v]) | Returns a new dictionary with keys from seq and value equal to v (defaults to None). |
get(key[,d]) | Returns the value of the key. If the key does not exist, returns d (defaults to None). |
items() | Return a new object of the dictionary's items in (key, value) format. |
keys() | Returns a new object of the dictionary's keys. |
pop(key[,d]) | Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises KeyError. |
popitem() | Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty. |
setdefault(key[,d]) | Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None). |
update([other]) | Updates the dictionary with the key/value pairs from other, overwriting existing keys. |
values() | Returns a new object of the dictionary's values |
Python Dictionary Built-in methods
Following are few Python Dictionary built-in methods
Function | Description |
---|---|
all() | Return True if all keys of the dictionary are True (or if the dictionary is empty). |
any() | Return True if any key of the dictionary is true. If the dictionary is empty, return False. |
len() | Return the length (the number of items) in the dictionary. |
cmp() | Compares items of two dictionaries. (Not available in Python 3) |
sorted() | Return a new sorted list of keys in the dictionary. |