Contents
Dictionary is another built-in data type which allows us to store a collection of key-value pairs.
As you can see in the image. Each element in a dictionary has two parts: a key and a value.
Think of Dictionary like a list, unlike a list, however, elements stored in the dictionary are stored in no particular order and we use a key to access a specific value. Most of the time key is a string, but it can be any immutable type such as int, float, tuple, string etc. Each key maps to a value, so we can’t have duplicate keys. Dictionaries are mutable objects which means we can add, remove, or update the elements after it is created.
Creating a Dictionary
We can create a dictionary using the following syntax:
1 2 3 4 5 6 |
variable_name = { 'key1' : 'value1', 'key2' : 'value2', ... 'keyN' : 'valueN', } |
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 |
>>> >>> contacts = { ... "tom": "122-444-333", ... "jim": "412-1231-121", ... "ron": "8912-121-1212", ... "jake": "333-1881-121" ... } >>> >>> contacts {'jim': '412-1231-121', 'jake': '333-1881-121', 'tom': '122-444-333', 'ron': '89 12-121-1212'} >>> |
This statement creates a dictionary of 4 elements. The key in the first element is "tom"
and it’s corresponding value is "122-444-333"
. The rest of the elements are created in the same manner. Although I have indented each element inside a dictionary, it is not required. It’s done here just for the sake of readability.
Note that the order in which the elements are displayed in the console is not the same order in which they are created. This shows that the elements in the dictionary are stored in no particular order.
To create an empty dictionary do this:
1 2 3 |
>>> >>> empty_dict = {} >>> |
Recall from lesson Sets in Python that we also use curly braces ({}
) to create sets. As {}
creates an empty dictionary, to create an empty set use set()
constructor function like this:
1 2 3 4 5 |
>>> >>> empty_set = set() # create an empty set >>> type(empty_set) <class 'set'> >>> |
We can also use dict()
constructor function to create a dictionary object but the syntax is little different. The dict()
function requires you to pass keyword arguments not the key-value pairs separated by a colon(:
). Here is how we can create the same contacts
dictionary using the dict()
constructor function.
1 2 3 4 5 6 7 8 |
>>> >>> dict_contacts = dict( ... tom = "122-444-333", ... jim = "412-1231-121", ... ron = "8912-121-1212", ... jake = "333-1881-121" ... ) >>> |
This statement creates the exact same dictionary. Some people prefer dict()
function over curly braces {}
because dict()
function don’t need quotation marks around the keys. Its just a matter of preference, you are free to choose whatever you want. Throughout this guide, we will use {}
syntax to create dictionaries.
Accessing Value from a Dictionary
As already discussed, the order of elements in a dictionary may vary. Consequently, we can’t use the element’s index position to access the value. Instead, we use a key. To access the value from the dictionary we use the following syntax:
1 |
dict_name[key] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
>>> >>> contacts = { ... "tom": "122-444-333", ... "jim": "412-1231-121", ... "ron": "8912-121-1212", ... "jake": "333-1881-121" ... } >>> >>> contacts['ron'] '8912-121-1212' >>> >>> contacts['tom'] '122-444-333' >>> |
If the specified key doesn’t exist, KeyError
exception will be raised.
1 2 3 4 5 6 7 |
>>> >>> contacts['jane'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'jane' >>> >>> |
Adding and Modifying Values
We can add a new element to a dictionary using the following syntax:
1 |
dict_name[key] = value |
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 |
>>> >>> contacts['jane'] = '443-123-991' # adding new element >>> >>> contacts { 'jim': '412-1231-121', 'jake': '333-1881-121', 'tom': '122-444-333', 'jane': '443-123-991', 'ron': '8912-121-1212' } >>> |
If the key already exists in the dictionary, then it’s value is updated.
1 2 3 4 5 6 7 |
>>> >>> contacts['jane'] = '443-123-000' # update Jane's number >>> >>> contacts['jane'] '443-123-000' >>> >>> |
Deleting Elements
To delete an element from a dictionary, we use the del
statement. The syntax of the del
statement is as follows:
1 |
del dict_name[key] |
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 |
>>> >>> del contacts['ron'] >>> >>> contacts { 'jim': '412-1231-121', 'jake': '333-1881-121', 'tom': '122-444-333', 'jane': '443-123-000' } >>> |
If the key doesn’t exist in the dictionary, KeyError
exception is raised.
1 2 3 4 5 6 |
>>> >>> del contacts['ron'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'ron' >>> |
Getting Length of Dictionary using len()
We can use the built-in len()
function to count the number of elements in a dictionary.
1 2 3 4 5 6 7 8 9 10 11 12 |
>>> >>> len(contacts) 4 >>> >>> contacts { 'jim': '412-1231-121', 'jake': '333-1881-121', 'tom': '122-444-333', 'jane': '443-123-000' } >>> |
Iterating through elements using for loop
We can use for loop to iterate through all the keys in the dictionary as follows:
1 2 3 4 5 6 |
>>> >>> for key in contacts: ... print(key, end=" ") ... jim jake tom jane >>> >>> |
Once we have a key we can access its corresponding value.
1 2 3 4 5 6 7 8 9 |
>>> >>> for key in contacts: ... print(key, ":" , contacts[key]) ... jim : 412-1231-121 jake : 333-1881-121 tom : 122-444-333 jane : 443-123-000 >>> |
Membership Operators with Dictionary
The in
and not in
operators can be used to test the existence of a key inside a dictionary. Here are some examples:
1 2 3 4 5 6 7 8 9 10 |
>>> >>> "jane" in contacts # Does key 'jane' exists in contacts ? True >>> >>> "ron" in contacts # Does key 'ron' exists in contacts ? False >>> >>> "tom" not in contacts # Doesn't key 'tom' exists in contacts False >>> |
Comparison Operators with Dictionary
We can use ==
and !=
operators to test whether two dictionaries contains the same elements or not.
1 2 3 4 5 6 7 8 9 10 |
>>> >>> marks1 = { 'larry': 90, 'bill': 60} >>> marks2 = { 'bill': 60, 'larry': 90} >>> >>> marks1 == marks2 True >>> >>> marks1 != marks2 False >>> |
The remaining comparison operators such as <
, <=
, >
and >=
can’t be used with dictionaries because elements in a dictionary are stored in no particular order.
Dictionary Methods
The following table lists some common methods we can call on a dictionary object.
Method | Description |
---|---|
keys() |
Returns a sequence containing only the keys from the dictionary. |
values() |
Returns a sequence containing only the values from the dictionary. |
items() |
Returns a sequence of tuples, where each tuple contains a key and value of an element. |
get(key, [default]) |
Returns the value associated with the key . If the key is not found it returns None . We can also provide an optional default value as the second argument in which case if the key is not found, the default value will be returned instead of None . |
pop(key) |
Returns the value associated with the key then removes the specified key and it's corresponding value from the dictionary. If the key doesn't exist KeyError exception is raised. |
popitem() |
Removes and return a random element from the dictionary as a tuple. |
copy() |
Creates a new copy of the dictionary. |
clear() |
Removes all the elements from the dictionary. |
keys() method
1 2 3 4 5 6 7 |
>>> >>> contacts.keys() dict_keys(['jim', 'jane', 'tom', 'jake']) >>> >>> type(contacts.keys()) <class 'dict_keys'> >>> |
The keys()
method returns a sequence of type dict_keys
. Think of dict_keys
object as an immutable list which you can use in a for loop or pass it’s result to other functions for further processing. If you want a list or tuple simply pass the result of keys()
method to list()
or tuple()
constructor as follows:
1 2 3 4 5 6 7 8 |
>>> >>> list(contacts.keys()) ['jim', 'jane', 'tom', 'jake'] >>> >>> tuple(contacts.keys()) ('jim', 'jane', 'tom', 'jake') >>> >>> |
values() method
1 2 3 4 5 6 7 8 9 10 11 12 13 |
>>> >>> contacts.values() dict_values(['412-1231-121', '443-123-000', '122-444-333', '333-1881-121']) >>> >>> type(contacts.values()) <class 'dict_values'> >>> >>> list(contacts.values()) ['412-1231-121', '443-123-000', '122-444-333', '333-1881-121'] >>> >>> tuple(contacts.values()) ('412-1231-121', '443-123-000', '122-444-333', '333-1881-121') >>> |
items() method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
>>> >>> contacts.items() dict_items([ ('jim', '412-1231-121'), ('jane', '443-123-000'), ('tom', '122-444-333'), ('jake', '333-1881-121') ]) >>> >>> >>> type(contacts.items()) <class 'dict_items'> >>> |
The items()
method returns a sequence of tuples, where each tuple contains key and value of an element. We can use a for loop to loop over tuples as follows:
1 2 3 4 5 6 7 8 9 10 |
>>> >>> for k, v in contacts.items(): ... print(key, ":", value) ... jim : 412-1231-121 jane : 443-123-000 tom : 122-444-333 jake : 333-1881-121 >>> >>> |
Notice that in the for loop we have two target variables key
and value
because tuple has two elements. The for loop iterates once for each tuple in the sequence. Each time the loop iterates, the first element (which is a key) is assigned to the variable k
and the second element (which is a value) is assigned to the variable v
. The process continues until there are elements in the dictionary.
get() method
1 2 3 4 5 6 7 8 9 10 |
>>> >>> print(contacts.get('jake')) 333-1881-121 >>> >>> print(contacts.get('paul')) None >>> >>> print(contacts.get('paul', "Not found")) Not found >>> |
pop() method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
>>> >>> contacts { 'jim': '412-1231-121', 'jane': '443-123-000', 'tom': '122-444-333', 'jake': '333-1881-121' } >>> >>> contacts.pop('jim') '412-1231-121' >>> >>> contacts { 'jane': '443-123-000', 'tom': '122-444-333', 'jake': '333-1881-121' } >>> >>> contacts.pop('jim') Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'jim' >>> |
popitem() method
1 2 3 4 5 6 7 |
>>> >>> contacts.popitem() ('jane', '443-123-000') >>> >>> contacts {'tom': '122-444-333', 'jake': '333-1881-121'} >>> |
copy() method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
>>> >>> contacts {'tom': '122-444-333', 'jake': '333-1881-121'} >>> >>> id(contacts) # address of contacts dictionary 4131208 >>> >>> copy_contacts = contacts.copy() # create a copy of the contacts dictionary >>> >>> copy_contacts {'jake': '333-1881-121', 'tom': '122-444-333'} >>> >>> id(copy_contacts) # address of copy_contacts dictionary 4131272 >>> |
clear() method
1 2 3 4 5 6 7 8 9 |
>>> >>> contacts.clear() # delete all the elements of a dictionary >>> >>> contacts {} >>> >>> copy_contacts # however, copy_contacts still contains a copy of the original dictionary object {'jake': '333-1881-121', 'tom': '122-444-333'} >>> |
Although, we have deleted the original contacts
dictionary, copy_contacts
still contains a copy of it.
Python course is very good,add some exercise examples for practice.
Hi,
Just wanted to thank you for this tutorial. Very clear and easy to follow.
Best regards,