Python
In this tutorial we will learn about dictionary in Python.
We briefly talked about dictionary in the Python - Data Type tutorial.
A dictionary is an unordered collection of key-value pairs.
We use curly { } brackets to create dictionary and separate key from value using : colon. Each pair of the dictionary is separated by , comma.
{ }
:
,
In the following example we are creating a dictionary of user data.
# dictionary user = { "username": "yusufshakeel", "isOnline": False, "score": 9.1 } # output print("type:", type(user)) print(user)
We will get the following output.
type: <class 'dict'> {'username': 'yusufshakeel', 'isOnline': False, 'score': 9.1}
dict()
We use the dict() constructor to create a dictionary in Python.
# dictionary user = dict(username = "yusufshakeel", isOnline = False, score = 9.1) #output print(user)
Output
{'username': 'yusufshakeel', 'isOnline': False, 'score': 9.1}
A dictionary item is a key-value pair so, to get the value we use the key.
Following is the syntax to get the value of a given key of a dictionary.
dictionary[key]
Where, dictionary represents a dictionary variable and key is some key whose value we are trying to access.
dictionary
key
In the following Python program we are printing the value saved in a "username" key of a "user" dictionary.
# dictionary user = { "username": "yusufshakeel", "isOnline": False, "score": 9.1 } # output print(user['username']) # yusufshakeel
If the key does not exists in the dictionary then we get an error.
get
We can also get the value of a key using the get method.
In the following Python program we are printing the score.
# dictionary user = { "username": "yusufshakeel", "isOnline": False, "score": 9.1 } # output print(user.get('score')) # 9.1
If the key does not exists then get will return None of NoneType class.
None
NoneType
In the following Python program we are trying to get the value of a key that does not exists.
# dictionary user = { "username": "yusufshakeel", "isOnline": False, "score": 9.1 } value = user.get('unknown') # output print("type:", type(value)) print("value:", value)
type: <class 'NoneType'> value: None
We use the following syntax to change the value of a dictionary item.
dictionary[key] = value
Where, dictionary represents a dictionary variable, key is some key whose value we want to change and value is the new value that we are assigning to the key.
value
In the following Python program we are assigning True to isOnline key.
True
# dictionary user = { "username": "yusufshakeel", "isOnline": False, "score": 9.1 } # change user['isOnline'] = True # output print(user)
Output:
{'username': 'yusufshakeel', 'isOnline': True, 'score': 9.1}
We take help of for loop to print all the keys of a dictionary.
In the following Python program we are printing out all the keys of the user dictionary.
# dictionary user = { "username": "yusufshakeel", "isOnline": False, "score": 9.1 } for k in user: print(k)
username isOnline score
To print the key-value pairs of a dictionary we take help of the for loop.
So, the for loop helps us to get the key of the dictionary. Then using the key we can access the value.
for
In the following Python program we are printing the key-value pairs.
# dictionary user = { "username": "yusufshakeel", "isOnline": False, "score": 9.1 } for k in user: print("key:", k, "value:", user[k])
key: username value: yusufshakeel key: isOnline value: False key: score value: 9.1
To check if a key exists in a given dictionary we take help of the in - membership operator.
The in operator will return True if the key exists. False otherwise.
in
False
In the following example we are checking the existence of some items in a given dictionary.
# dictionary user = { "username": "yusufshakeel", "isOnline": False, "score": 9.1 } # output print("username" in user) # True print("score" in user) # True print("unknown" in user) # False
We use the len method to count the total number of items (key-value pairs) present in a given dictionary.
len
In the following Python program we are printing the total number of items.
# dictionary user = { "username": "yusufshakeel", "isOnline": False, "score": 9.1 } # output print(len(user)) # 3
We use the following syntax to add a new item to an existing dictionary.
Where, dictionary represents a dictionary variable and key is the new item key that we want to add to the dictionary and value is the value of the new item.
In the following Python program we are adding a new item to the user dictionary.
# dictionary user = { "username": "yusufshakeel", "isOnline": False, "score": 9.1 } # new item user["level"] = 1 # output print(user)
{'username': 'yusufshakeel', 'isOnline': False, 'score': 9.1, 'level': 1}
We use the pop method to pop (remove) items from a given dictionary.
pop
In the following example we are popping out "level" item from the user dictionary.
# dictionary user = { "username": "yusufshakeel", "isOnline": False, "score": 9.1, "level": 1 } # pop itemValue = user.pop('level') # output print(itemValue) # 1 print(user) # {'username': 'yusufshakeel', 'isOnline': False, 'score': 9.1}
Note! The pop method will remove the item from the list and will return the value that was removed which we can save in some variable.
We can also use the del keyword to delete items from the dictionary.
del
In the following Python program we are deleting "level" from the user dictionary using the del keyword.
# dictionary user = { "username": "yusufshakeel", "isOnline": False, "score": 9.1, "level": 1 } # delete del user['level'] # output print(user) # {'username': 'yusufshakeel', 'isOnline': False, 'score': 9.1}
We can also use the del keyword to completely delete the dictionary and all the items.
In the following Python program we are deleting the user dictionary.
# dictionary user = { "username": "yusufshakeel", "isOnline": False, "score": 9.1, "level": 1 } # delete del user