(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
Python Dictionaries
Updated on Jan 07, 2020
Dictionary is a python data type that is used to store key-value pairs. It enables you to quickly retrieve, add, remove, modify, values using a key. Dictionary is very similar to what we call associative array or hash on other languages.
note:
Dictionaries are mutable.
Creating a Dictionary #
Dictionaries can be created using a pair of curly braces ({}
). Each item in the dictionary consists of a key, followed by a colon, which is followed by a value. And each item is separated using commas (,
). Let's take an example.
1 2 3 4 | friends = {
'tom' : '111-222-333',
'jerry' : '666-33-111'
}
|
here friends
is a dictionary with two items. One point to note that key must be of a hashable type, but the value can be of any type. Each key in the dictionary must be unique.
>>> dict_emp = {} # this will create an empty dictionary
Retrieving, modifying and adding elements in the dictionary #
To get an item from the dictionary, use the following syntax:
>>> dictionary_name['key']
1 2 | >>> friends['tom']
'111-222-333'
|
If the key exists in the dictionary, the value will be returned, otherwise a KeyError
exception will be thrown. To add or modify an item, use the following syntax:
>>> dictionary_name['newkey'] = 'newvalue'
1 2 3 | >>> friends['bob'] = '888-999-666'
>>> friends
{'tom': '111-222-333', 'bob': '888-999-666', 'jerry': '666-33-111'}
|
Deleting Items from the dictionary. #
>>> del dictionary_name['key']
1 2 3 | >>> del friends['bob']
>>> friends
{'tom': '111-222-333', 'jerry': '666-33-111'}
|
If the key is found the item will be deleted, otherwise a KeyError
exception will be thrown.
Looping items in the dictionary #
You can use for loop to traverse elements in the dictionary.
1 2 3 4 5 6 7 8 9 10 11 12 | >>> friends = {
... 'tom' : '111-222-333',
... 'jerry' : '666-33-111'
...}
>>>
>>> for key in friends:
... print(key, ":", friends[key])
...
tom : 111-222-333
jerry : 666-33-111
>>>
>>>
|
Find the length of the dictionary #
You can use the len()
function to find the length of the dictionary.
1 2 | >>> len(friends)
2
|
in or not in operators #
in
and not in
operators to check whether key exists in the dictionary.
1 2 3 4 | >>> 'tom' in friends
True
>>> 'tom' not in friends
False
|
Equality Tests in dictionary #
The ==
and !=
operators tells whether dictionary contains the same items not.
1 2 3 4 5 6 7 | >>> d1 = {"mike":41, "bob":3}
>>> d2 = {"bob":3, "mike":41}
>>> d1 == d2
True
>>> d1 != d2
False
>>>
|
note:
You can't use other relational operators like <
, >
, >=
, <=
to compare dictionaries.
Dictionary methods #
Python provides several built-in methods for working with dictionaries.
Methods | Description |
---|---|
popitem() |
Returns randomly selected item from the dictionary and also remove the selected item. |
clear() |
Delete everything from a dictionary |
keys() |
Return keys in the dictionary as tuples |
values() |
Return values in dictionary as tuples |
get(key) |
Return value of key, if key is not found it returns None , instead of throwing KeyError exception |
pop(key) |
Remove the item from the dictionary, if the key is not found KeyError will be thrown |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | >>> friends = {'tom': '111-222-333', 'bob': '888-999-666', 'jerry': '666-33-111'}
>>>
>>> friends.popitem()
('tom', '111-222-333')
>>>
>>> friends.clear()
>>>
>>> friends
{}
>>>
>>> friends = {'tom': '111-222-333', 'bob': '888-999-666', 'jerry': '666-33-111'}
>>>
>>> friends.keys()
dict_keys(['tom', 'bob', 'jerry'])
>>>
>>> friends.values()
dict_values(['111-222-333', '888-999-666', '666-33-111'])
>>>
>>> friends.get('tom')
'111-222-333'
>>>
>>> friends.get('mike', 'Not Exists')
'Not Exists'
>>>
>>> friends.pop('bob')
'888-999-666'
>>>
>>> friends
{'tom': '111-222-333', 'jerry': '666-33-111'}
|
In the next post, we will learn about Python tuples.
Other Tutorials (Sponsors)
This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!
View Comments