In this tutorial, you’ll learn what is Python dictionary and how to create it. It will also teach you how to add/append to a Python dictionary, sort it by value, search, iterate, and remove elements.
A dictionary in Python is a scrambled collection of objects. Unlike other data types such as a list or a set that has a single value field, the dictionary type stores a key along with its value.
The keys pair with values using a colon (:) while the commas work as a separator for the elements. Also, the entire dictionary object uses curly braces to enclose itself.
Check Out: Some of the Best Examples of Using the Python Dictionary
Below is an example of a barren dictionary object which doesn’t have any elements.
#The empty Python dictionary object {}
Please remember that only keys inside a dictionary can’t have duplicates, but their values can repeat themselves.
Next, the value in a dictionary can be of any valid Python data type. But the keys have a constraint to be of any immutable data type such as a string, a number, or a tuple. To learn more on this topic, please continue with the tutorial.
Understanding Dictionary in Python
Firstly, let’s see how to create a dictionary in Python. And secondly, we’ll see how to add/append elements to the Python dictionary. And thirdly, you’ll learn how to sort a dictionary in Python and check if a key exists in the dictionary.
Furthermore, this tutorial will teach you how to iterate through a dictionary in Python. And, it will also walk you through various dictionary operations like append, update, and remove elements from it.
How to create a dictionary in Python?
If you wish to create a Python dictionary with fixed keys and values, then it’s quite easy to do so. Just combine all the “key1:value1, key2:value2,…” pairs and enclose them with curly braces.
The combination of a key and its value, i.e. “key: value” represents a single element of a dictionary in Python.
While defining static dictionary objects, you must be careful to use unique values for keys. However, they can derive from any valid Python data type.
Also, remember to use only immutable data types for the values while they can have duplicates.
1. How to create an empty dictionary in Python?
Using curly braces is the most common way to create a dictionary.
# Define a blank dictionary with no elements blank_dict = {}
2. How to create a dictionary from the list in Python?
By using the dict()
function, we can create a dictionary in Python.
key_value_pairs = [('a', 1), ('b', 2), ('c', 3)] # Create a dictionary from the key-value pairs dict = dict(key_value_pairs) # Print the dictionary print(dict)
The following code creates a dictionary from two lists using the Python zip() function.
keys = ['a', 'b', 'c'] values = [1, 2, 3] # Create a list of key-value pairs from the two lists key_value_pairs = zip(keys, values) # Create a dictionary from the key-value pairs dict = dict(key_value_pairs) # Print the dictionary print(dict)
3. Using the fromkeys()
function: This function creates a dictionary with a sequence of keys and a default value.
The syntax is: dict.fromkeys(keys, default_value)
. where keys
are a sequence of keys, and default_value
is the value to be used for keys that do not exist in the dictionary.
For example, the following code creates a dictionary with three keys and a default value of 0:
keys = ['name', 'age', 'city'] # Create a dictionary with default value 0 dict = dict.fromkeys(keys, 0)
Learn about – Python Strings
How to add/append to a dictionary in Python?
There are several ways to add elements to a dictionary in Python. Here are some of the most common methods:
1. Using the assignment operator: This is the simplest way to add an element to a dictionary. Simply assign a value to a new key in the dictionary. For example:
dict = {'name': 'Srinivasa Ramanujan'} # Add a new key-value pair to the dictionary dict['age'] = 30 # Print the dictionary print(dict)
2. Using the update() method: The update() method allows you to append multiple key-value pairs to the Python dictionary at once. The syntax is: dict.update({'key': 'value'})
dict = {'name': 'Chitranjan Sri'} # Add multiple key-value pairs to the dictionary dict.update({'age': 30, 'city': 'New York'}) # Print the dictionary print(dict)
3. Using the ** operator: The ** operator allows you to “unpack” a dictionary into a set of key-value pairs. This can be useful when you want to add multiple key-value pairs to a dictionary from a list or other iterable object.
The syntax is: dict = {**{'key': 'value'}, **{'key2': 'value2'}}
keys = ['name', 'age', 'city'] values = ['Varsha Dave', 30, 'New York'] # Create a dictionary from the keys and values dict = {**dict, **dict.fromkeys(keys, values)} # Print the dictionary print(dict)
4. Using the extend() method: The extend() method takes an iterable as its argument and appends each element to the Python dictionary.
dict = {'name': 'Dasa Griva', 'age': 30} # Create a list of key-value pairs new_dict_items = [('occupation', 'software engineer'), ('city', 'New York')] # Append the list of key-value pairs to the dictionary dict.extend(new_dict_items) # Print the dictionary print(dict)
5. Using the + operator: The + operator can be used to combine two dictionaries. The new dictionary will contain all of the key-value pairs from the first dictionary and the second dictionary.
dict1 = {'name': 'Arya bhatt', 'age': 30} dict2 = {'occupation': 'software engineer', 'city': 'New York'} # Combine the two dictionaries new_dict = dict1 + dict2 # Print the new dictionary print(new_dict)
How to sort a dictionary in Python?
There are a variety of ways to sort a dictionary in Python. Here, you’ll see some of the most common methods:
1. Using the sorted() function: The sorted() function can be used to sort any iterable object, including dictionaries. The syntax is: sorted(dict, key=lambda x: x[key])
In the syntax, the dict
is the dictionary for sorting. And key
is a function that takes a key-value pair from the dictionary and returns a value to sort the dictionary.
For example, to sort a dictionary by the values, you would use the following code:
dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4} # Sort the dictionary by values sorted_dict = sorted(dict, key=lambda x: x[1]) # Print the sorted dictionary print(sorted_dict) # result: [('c', 3), (a', 1), (d', 4), (b', 2)]
2. Using the items() method: The items() method returns an iterable object that contains the key-value pairs of a dictionary. This iterable object can then be sorted using the sorted() function. For example:
dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4} # Get the key-value pairs of the dictionary items = dict.items() # Sort the key-value pairs sorted_items = sorted(items) # Print the sorted key-value pairs print(sorted_items) # result: [('a', 1), (b', 2), (c', 3), (d', 4)]
3. Using the OrderedDict() class: The OrderedDict() class is a subclass of the dictionary class that maintains the order of the key-value pairs when it is created.
This means that you can sort a Python OrderedDict by key by simply calling the sort() method on it. For example:
from collections import OrderedDict dict = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)]) # Sort the dictionary dict.sort() # Print the sorted dictionary print(dict) # result: OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
How to check if a key exists in a dictionary?
You can many ways to check if a key exists in a dictionary in Python. Here, we lay down some of the most common methods:
1. Using the in operator: The in operator can be used to check if a value is present in a sequence, such as a list or a tuple.
It can also be used to check if a key exists in a dictionary. The syntax is: key in dict
In the syntax, dict
is the dictionary and key
is the key to be checked. For example, the following code checks if the key ‘a’ exists in the dictionary:
dict = {'a': 1, 'b': 2, 'c': 3} # Check if the key 'a' exists in the dictionary if 'a' in dict: print('The key exists in the dictionary') else: print('The key does not exist in the dictionary')
2. Using the get() method: The get() method returns the value associated with a key in a dictionary. If the key does not exist, the get() method returns None.
The syntax is: dict.get(key, default_value)
, where dict
is the dictionary, key
is the key to be checked, and default_value is the value to be returned if the key does not exist.
For example, the following code checks if the key ‘a’ exists in the dictionary dict
and prints the value associated with the key if it exists:
dict = {'a': 1, 'b': 2, 'c': 3} # Check if the key 'a' exists in the dictionary and print the value value = dict.get('a') if value is not None: print(value) else: print('The key does not exist in the dictionary')
3. Using the keys() method: The keys() method returns an iterable object that contains all of the keys in a dictionary. This iterable object can then be used to check if a specific key exists in the dictionary.
For example, the following code checks if the key ‘a’ exists in the dictionary dict
by looping over the keys() method:
dict = {'a': 1, 'b': 2, 'c': 3} # Check if the key 'a' exists in the dictionary by looping over the keys() method for key in dict.keys(): if key == 'a': print('The key exists in the dictionary') break else: print('The key does not exist in the dictionary')
Also, don’t miss out on learning how to reverse a list in Python.
How to iterate through a dictionary?
Similar to the lists, you can use a “for in” loop to traverse through a dictionary. In general, it’s the keys that enable iteration.
Let’s understand the concept with a simple example. It prints all the keys of a dictionary in a loop.
dict = {'Student Name': 'Berry', 'Roll No.': 12, 'Subject': 'English'} print("Keys are:") for key in dict: print(key)
The output of the above Python code is as follows.
Keys are: Student Name Roll No. Subject
Follow one more example below which prints keys along with values.
dict = {'Student Name': 'Berry', 'Roll No.': 12, 'Subject': 'English'} print("{Keys}:{Values}") for key, value in dict.items(): print({key},":",{value})
The result of the above Python code is as follows.
{Keys}:{Values} {'Student Name'} : {'Berry'} {'Roll No.'} : {12} {'Subject'} : {'English'}
How to remove elements in a dictionary?
Python lends us a no. of methods to remove elements from the dictionary.
The most common of them is the “pop()” method. It takes the key as the input and deletes the corresponding element from the Python dictionary. It returns the value associated with the input key.
Another method is “popitem()”. It removes and returns a random element (key, value) from the dictionary.
If you like to drop all the elements from the dictionary, then use the “clear()” method to flush everything.
Nonetheless, one more way to remove an element from a dictionary is to use the del keyword. It can help you delete individual items and consequently the whole dictionary object.
# Create a Python dictionary sixMonths = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30} # Delete a specific element print(sixMonths.pop(6)) print(sixMonths) # Delete an random element print(sixMonths.popitem()) print(sixMonths) # Remove a specific element del sixMonths[5] print(sixMonths) # Delete all elements from the dictionary sixMonths.clear() print(sixMonths) # Finally, eliminate the dictionary object del sixMonths print(sixMonths)
Here is the result of running the above coding snippet.
30 {1: 31, 2: 28, 3: 31, 4: 30, 5: 31} (1, 31) {2: 28, 3: 31, 4: 30, 5: 31} {2: 28, 3: 31, 4: 30} {} Traceback (most recent call last): File "C:/Python/Python35/test_dict.py", line 22, in <module> print(sixMonths) NameError: name 'sixMonths' is not defined
In the above example, the second last statement removes all the elements from the Python dictionary, leaving it empty.
In addition, the subsequent call to the “del” operator on the dictionary object removes it altogether. Hence, the last print statement fails with the “NameError.”
Learn about – Tuples in Python
Define dictionary attributes
Python doesn’t impose any constraints on the “Values” of a dictionary object. You can form them using standard Python or any custom data type. But, as we said earlier, the “Keys” aren’t the same as “Values” and have altogether different handling.
Hence, it is vital for you to memorize the following two facts about the dictionary “Keys.”
- The same key can’t have another value in the dictionary. It confirms that a duplicate key can’t exist. However, even if you try to supply a duplicate key, it’ll only modify the existing key with the value provided in the last assignment.
dict = {'Student Name': 'Berry', 'Roll No.': 12, 'Subject': 'English','Student Name': 'Kerry'} print("dict['Student Name']: ", dict['Student Name'])
Executing the above code will show that the key “Student Name” will keep the last assigned value, i.e., “Kerry.”
dict['Student Name']: Kerry
- Python says that the dictionary Keys should derive from immutable data types. You can infer that the only allowed types are strings, numbers, or tuples. Check out a standard example below.
dict = {['Student Name']: 'Berry', 'Roll No.': 12, 'Subject': 'English'} print("dict['Student Name']: ", dict['Student Name'])
In the above example, the key is using a list type. Since Python doesn’t support this, the statement will generate a “TypeError.”
Here is the outcome of the above example.
Traceback (most recent call last): File "C:/Python/Python35/test_dict.py", line 1, in <module> dict = {['Student Name']: 'Berry', 'Roll No.': 12, 'Subject': 'English'} TypeError: unhashable type: 'list'
Learn about – Python list comprehension
Dictionary comprehension in Python
Just like a Python list, the dictionary also allows comprehension to create new objects from an iterable inside loop.
You can specify a dictionary comprehension by using an expression including a “key: value” pair followed by for loop and enclosed with curly braces {}.
Follow the below examples to create a dictionary using the comprehension syntax.
Let’s make a dictionary object with the string type for keys and the number format for values.
>>> {str(iter):iter for iter in [11,22,33,44,55]} {'44': 44, '33': 33, '55': 55, '11': 11, '22': 22}
Another example of creating a dictionary from the list of weekdays as keys and the length of each week as the values.
>>> weekdays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] >>> {w:len(w) for w in weekdays} {'fri': 3, 'tue': 3, 'wed': 3, 'sat': 3, 'thu': 3, 'mon': 3, 'sun': 3}
We can use the Python enumerate() function in dictionary comprehension. It helps us save the index of a specific element that we could use later. Also, in a for loop, the position of a list element isn’t visible without “enumerate().”
Such Python dictionaries which have element indexes can be useful in many situations.
>>> {w : i for i, w in enumerate(weekdays)} {'fri': 5, 'tue': 2, 'wed': 3, 'sat': 6, 'thu': 4, 'mon': 1, 'sun': 0}
How to test for membership in a dictionary?
We can quickly confirm whether a Key is present in a dictionary or not using the keyword “in.” Also, please note that the membership test is only applicable to Keys, not to Values.
weekdays = {'fri': 5, 'tue': 2, 'wed': 3, 'sat': 6, 'thu': 4, 'mon': 1, 'sun': 0} # Output: True print('fri' in weekdays) # Output: False print('thu' not in weekdays) # Output: True print('mon' in weekdays)
The output of the above snippet is as follows.
True False True
Must Read: Convert a Python Dictionary to JSON
Summary – Python Dictionary
From this tutorial, you must have learned how to add/append to a Python dictionary, search, sort, iterate, and more. In whatever domain of Python, you choose to work, knowing dictionaries will surely help.
Now, if you’ve learned something from this lesson, then care to share it with your colleagues. Also, connect to our social media accounts to receive timely updates.
Best,
TechBeamers