Python Dictionary
About Python Dictionary
In Python, a dictionary is used to store a collection of key-value pairs.
Each key in a dictionary must be unique and immutable, and it is used to access its corresponding value.
Creating a dictionary
You can create a dictionary by enclosing key-value pairs inside curly braces '{}'.
Key and value must be paired by colon ':' and each key-value pair must be seperated by comma (,).
In the following example, my_dict = {'name': 'David', 'age': 50, 'city': 'Sydney'} is an example of dictionary where my_dict is the variable of the dictionary and 'name', 'age', and 'city' are the keys and 'David', 50, and 'Sydney' are the vaules. Each key and value are paired with colon (:) e.g. 'name': 'David'.
Please have a colser look at the following example.
Example of creating dictionary:
Output of the above example
{'name': 'David', 'age': 50, 'city': 'Sydney'}
Accessing value of a key in a dictionary
You can access the value associated with a key by defining the key inside square brackets '[]'.
In the following example, person_name = person_dict['name'] is used to get the value of 'name' key and assigned it to the person_name variable. The key 'name' is placed inside square brackets '[]'.
Example of accessing value of a key:
Output of the above example
David
Adding or modifying elements of a dictionary
Add element: You can add a new key-value pair by simply assigning a value to a new key.
In the first example, person_dict['age'] = 25 is used to add a new element to the dictionary where 'age' is the key and 25 is the value of the key.
Modify element: You can modify an existing element by simply assigning a value to an existing key.
In the second example, person_dict['age'] = 50 is used to modify the existing element of the dictionary where 'age' is the existing key and 50 is the new value of the key.
Examples of adding or modifying elements of a dictionary:
Output of the above example
Age element added: {'name': 'David', 'city': 'Sydney', 'age': 25}
Age element modified: {'name': 'David', 'city': 'Sydney', 'age': 50}
Removing element from a dictionary
You can remove a key-value pair from a dictionary using the del keyword or the pop() method. You need to specify the key of the element in both cases.
del:In the first example, del person_dict['age'] is used to remove element with key 'age' from the dictionary.
pop():In the second example, removed_element = person_dict.pop('city') is used to remove element with key 'city' from the dictionary where removed value is assigned to the removed_element variable.
The pop() method returns the value of removed element.
Examples of removing element from a dictionary:
Output of the above example
After removing age: {'name': 'David', 'city': 'Sydney'}
Removed value: Sydney
After using pop('city'): {'name': 'David'}
Iterating through the elements of dictionary
In Python, you can iterate through the keys and values of dictionary.
The value can be retrieved using the values() method while looping through the dictionary.
The key and corresponding value can be retrieved at the same time using the items() method while looping through the dictionary.
In the following example, grade_dic = {"English": "A+", "Math": "A", "Physics": "A+"} is a dictionary with variable with 'grade_dic' and {"English": "A+", "Math": "A", "Physics": "A+"} are key-value pairs.
In the first example, for key in grade_dic: is used to iterate (loop) through the dictionary variable 'grade_dic' to retrive the keys of the dictionary.
In the second example, for value in grade_dic.values(): is used to iterate (loop) through the dictionary variable 'grade_dic' and to retrive the values of the dictionary using values() method.
In the third example, for k, v in grade_dic.items(): is used to iterate (loop) through the dictionary variable 'grade_dic' where 'k' denotes key, 'v' denotes value, and items() method is used to retrive the key and corresponding value of the dictionary. print(k, v) prints the elements of dictionary.
Examples of iterating through the dictionaries:
Output of the above example
Keys are: English Math Physics Values are: A+ A B Keys and Values are: English A+ Math A Physics B
Dictionary methods
In Python, you can use several built-in methods for dictionary such as clear(), copy(), get(), items(), keys(), values(), pop(), popitem(), update(), setdefault().
1. clear(): The clear() method removes all items from the dictionary. In the following example, car_dic.clear() is used to remove all items from the dictionary car_dic = {'brand':'Toyota', 'model': 2020}.
Example of clear() method:
Output of the above example
{}
2. copy(): The copy() method copies a shallow copy of the dictionary. In the following example, new_dic = car_dic.copy() is used to copy the dictionary and create a new dictionary assigning the returned copy to the new_dic variable.
Example of copy() method:
Output of the above example
{'brand': 'Toyota', 'model': 2020}
3. get(): The get() method returns tha value of a specified key if it exists in the dictionary, otherwise it returns the default value if value is provided. If default value is not provided, it returns 'None'. In the following example, value = car_dic.get('brand') is used to get the value of 'brand' key from the dictionary.
Example of get() method:
Output of the above example
The existing value: Toyota The default value is: BMW
Python Compiler For Live Practice
Practice the above Python code in the following Python Editor. Create more Python dictionaries and try different methods and functions on the keys and values of the elements of the dictionaries in the following Python code editor and click Execute button to check the output. Output will be displayed in Python Code Output section.
Python Editor