In this tutorial, we will discuss a very useful data type: Python dictionary. We will also learn how to create a dictionary and learn all the functions and methods associated with it.
Python Dictionary
A python dictionary is an unordered collection of elements with a key : value pair. Each key is associated with a value. Here keys are immutable items and values could be mutable or immutable.
Create a Dictionary
To create a dictionary we use { } curly bracket, inserted key : value pairs and separate them with a comma (,). Remember when you create a dictionary each key should have a corresponding value. We can also use dict() function to create a dictionary
Dictionary Syntax:
dictionay_name = {key_1: value_1 , key_2: value_2 , key_3 : value_3 }
# dict() function syntax
dictionary_name = dict( [[key_1,value1 ], [key_2,value_2], [key_3, value_3]] )
Example:
dict_1 = {"hello":"world", "language":"python", "topic":"dictionary" } #using curly braces key:value
dict_2 = dict([["hello", "world"], ["language","python"], ["topic","dictionary"]]) #using dict() function
print(dict_1)
print(dict_2)
# Output
{'hello': 'world', 'language': 'python', 'topic': 'dictionary'}
{'hello': 'world', 'language': 'python', 'topic': 'dictionary'}
Access elements from a dictionary
Dictionary is an unordered collection of key and value pairs, so there is no concept of using an index that’s why we use the key to retrieve its corresponding value. We can use square brackets and get() function with the key to get the corresponded value.
Example
dict_1 = {"hello":"world", "language":"python", "topic":"dictionary" }
dict_2 = dict([["hello", "world"], ["language","python"], ["topic","dictionary"]])
print(dict_1['hello']) # using square bracket
print(dict_2.get('hello')) #using get method
#output
world
world
The difference between using a square bracket and get() method
If we pass a wrong key in a square bracket then it will throw an error (Key error), but get() will return None value.
Example Pass wrong key in get method
dict_1 = {"hello":"world", "language":"python", "topic":"dictionary" }
dict_2 = dict([["hello", "world"], ["language","python"], ["topic","dictionary"]])
print(dict_2.get('hell')) #uing get method
#Output
None
pass wrong key in square bracket
dict_1 = {"hello":"world", "language":"python", "topic":"dictionary" }
dict_2 = dict([["hello", "world"], ["language","python"], ["topic","dictionary"]])
print(dict_2['hell']) #using get method
#Output
KeyError: 'hell'
Add elements in a Dictionary:
Dictionaries are mutable, though keys of a dictionary are immutable but the mutability concept of a data type concern with the values not with index or key. With the help of its key with can change its corresponding value using an assignment operator.
Example:
info_cad = {'name':'Steve', 'course': 'c++', 'level':6
print('dictionary before any changes:',info_cad)
info_cad['level'] = 7
info_cad['course'] = 'python'
print("dictionary after the changes:", info_cad)
#Output
dictionary before any changes: {'name': 'Steve', 'course': 'c++', 'level': 6}
dictionary after the changes: {'name': 'Steve', 'course': 'python', 'level': 7}
Delete elements from a Dictionary:
We can use the pop() method to remove the specific key and value pair from a dictionary. We can also use clear() method to clear or remove all items of a dictionary.
Example:
factorial = {0:1, 1:1, 2:2, 3:6, 4:24, 5:120}
print(factorial.pop(5))
print("factorial dictionary after pop operation:", factorial)
factorial.clear()
print("factorial dictionary after clear meathod:", factorial)
#Output
120
factorial dictionary after pop operation: {0: 1, 1: 1, 2: 2, 3: 6, 4: 24}
factorial dictionary after clear meathod: {}
Dictionary Methods:
- clear()
- copy()
- fromkeys(seq[, v])
- get(key[,d])
- items()
- keys()
- pop(key[,d])
- popitem()
- setdefault(key[,d]) .
- update([other])
- values()
Dictionary Comprehension:
Dictionary comprehension is a technique of forming dictionary key : value pairs using an iterable.
Example:
mulitiple_6 = { x : x*6 for x in range(1,10) }
print(mulitiple_6)
#Output
{1: 6, 2: 12, 3: 18, 4: 24, 5: 30, 6: 36, 7: 42, 8: 48, 9: 54}
The above code is similar to:
mulitiple_6 = {}
for x in range(1,10):
mulitiple_6[x] = x*6
print(mulitiple_6)
#output
{1: 6, 2: 12, 3: 18, 4: 24, 5: 30, 6: 36, 7: 42, 8: 48, 9: 54}
Dictionary Operation:
1. keyword with a dictionary:
We use in keyword with a dictionary to check whether a key is present in that dictionary or not, remember the in keyword does not tell the value present in the dictionary the only key.
Example:
check = {1:2, 'hello':"world", 'course':'python' }
print("check whether the 2 key is in the dictionary: ", 2 in check )
print("check whether the key hello is in the dictionary: ", 'hello' in check)
#Output
check whether the 2 key is in the dictionary: False
check whether the key hello is in the dictionary: True
2. Dictionary as an iterable
We can use for loop to iterate through all the keys of a dictionary.
Example
my_dict = {0: 1, 'age': 70, 'level':8}
for i in my_dict:
print(i)
#Output
0
age
level