Dictionary in Python

Dictionary is another built-in data type which allows us to store a collection of key-value pairs.

A dictionary

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:

Here is an example:

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:

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:

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.

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:

If the specified key doesn’t exist, KeyError exception will be raised.

Adding and Modifying Values

We can add a new element to a dictionary using the following syntax:

Here is an example:

If the key already exists in the dictionary, then it’s value is updated.

Deleting Elements

To delete an element from a dictionary, we use the del statement. The syntax of the del statement is as follows:

Here is an example:

If the key doesn’t exist in the dictionary, KeyError exception is raised.

Getting Length of Dictionary using len()

We can use the built-in len() function to count the number of elements in a dictionary.

Iterating through elements using for loop

We can use for loop to iterate through all the keys in the dictionary as follows:

Once we have a key we can access its corresponding value.

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:

Comparison Operators with Dictionary

We can use == and != operators to test whether two dictionaries contains the same elements or not.

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

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:

values() method

items() method

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:

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

pop() method

popitem() method

copy() method

clear() method

Although, we have deleted the original contacts dictionary, copy_contacts still contains a copy of it.

2 thoughts on “Dictionary in Python

Leave a Comment

%d bloggers like this: