Page Contents
Basic Introduction
In Python, a dictionary is a collection of key-value pairs. It is a mutable, unordered collection that allows you to store data in the form of key-value pairs. Each key in a dictionary must be unique, and it is used to access its corresponding value. Keys must be immutable, meaning they cannot be changed after they are created. Values in a dictionary can be of any data type, including other dictionaries.
Starting from Python 3.7, dictionaries are guaranteed to maintain insertion order. This means that when you iterate over a dictionary, the order in which items were inserted will be preserved. This change was made to the Python language specification, and it’s also reflected in the built-in dict
type.
Here is an example:
# Creating a dictionary my_dict = { "name": "Shivaay", "age": 6, "city": "Delhi" } # Adding a new key-value pair my_dict["gender"] = "Male" # Iterating over key-value pairs for key, value in my_dict.items(): print(key, ":", value) # Output name : Shivaay age : 6 city : Delhi gender : Male
Before Python 3.7, dictionaries did not guarantee any specific order for their items. However, in Python 3.6, due to the implementation details of CPython, dictionaries were often observed to maintain insertion order in practice. But it was not guaranteed by the language specification. Starting from Python 3.7, this behavior became guaranteed and part of the language specification itself.
Read python Dictionary items
Reading from a Python dictionary involves accessing its values using keys. You can do this using square brackets []
with the key inside or using the get()
method if you’re not sure whether the key exists or not. Here’s how you can read from a dictionary:
Accessing Values by Key:
You can access values from a dictionary directly by using the key inside square brackets []
person = {"name": "Shivaay", "location": "Delhi", "age": 6} # Accessing values using keys print("Name: ", person["name"]) print("Age: ", person["age"]) print("Location: ", person["location"]) # Output Name: Shivaay Age: 6 Location: Delhi
Using the get()
Method:
The get()
method allows you to specify a default value if the key is not found in the dictionary.
fruit = { "fruit": "Banana", "size": "Medium", "color": "Yellow" } fruit_name = fruit.get("fruit","NOT FOUND") fruit_size = fruit.get("size","NOT FOUND") fruit_color = fruit.get("color","NOT FOUND") fruit_name_dummy = fruit.get("dummy","NOT FOUND") print("fruit_name: ",fruit_name) print("fruit_size: ",fruit_size) print("fruit_color: ",fruit_color) print("fruit_name_dummy: ",fruit_name_dummy) # Output fruit_name: Banana fruit_size: Medium fruit_color: Yellow fruit_name_dummy: NOT FOUND
Iterating Over Keys:
You can iterate over the keys in the dictionary using a loop.
print("Iterating over Keys of dictionary.") for key in fruit: print("Key: ", key) # Output Iterating over Keys of dictionary. Key: fruit Key: size Key: color for key in fruit.keys(): print("Key: ", key) # Output Key: fruit Key: size Key: color
Iterating Over Key-Value Pairs:
You can iterate over the key-value pairs in the dictionary using the items()
method:
person = {"name": "Proedu.co", "location": "Delhi", "age": 10} print("Iterating Over Key-Value Pairs.") for key, value in person.items(): print("Key: ", key, ", Value: ", value) # Output Iterating Over Key-Value Pairs. Key: name , Value: Proedu.co Key: location , Value: Delhi Key: age , Value: 10
Checking for Key Existence:
You can check if a key exists in the dictionary using the in
keyword:
fruit = { "fruit": "Banana", "size": "Medium", "color": "Yellow" } print("Checking for Key Existence.") if "color" in fruit: print("Key 'Color' is present in fruit dictionary.") else: print("Key 'Color' is NOT present in fruit dictionary.") # Output Checking for Key Existence. Key 'Color' is present in fruit dictionary.
Iterating over dictionary values():
The values()
method will return a list of all the values in the dictionary.
fruit = { "fruit": "Banana", "size": "Medium", "color": "Yellow" } x = fruit.values() print("Values: ", x) # Adding a new key-value pair in fruit dictionary. fruit["price"] = 100 print("Values: ", x) # Output Values: dict_values(['Banana', 'Medium', 'Yellow']) Values: dict_values(['Banana', 'Medium', 'Yellow', 100]) print("Looping Over dictionary values()") for value in x: print("Value: ", value) # Output Looping Over dictionary values() Value: Banana Value: Medium Value: Yellow Value: 100
Change python Dictionary values
To change the items in a Python dictionary, you can simply assign new values to the existing keys or by using update
method.
Assign new values to existing key
person = {"name": "Shivaay", "location": "Delhi", "age": 6} print("Dictionary Before: ",person) # Changing value of an existing key "name". person["name"] = "Shivaay Singh Chauhan" print("Dictionary After: ",person) # Output Dictionary Before: {'name': 'Shivaay', 'location': 'Delhi', 'age': 6} Dictionary After: {'name': 'Shivaay Singh Chauhan', 'location': 'Delhi', 'age': 6}
Using update
method
You can also use the update()
method to update multiple items in the dictionary at once by providing another dictionary containing the items to be updated or added:
person = {"name": "Prakash", "age": 30, "city": "Delhi"} print("Dictionary Before: ",person) # Changing value of an existing key "name". person.update({"age": 35, "occupation": "Engineer"}) print("Dictionary After: ",person) # Output Dictionary Before: {'name': 'Prakash', 'age': 30, 'city': 'Delhi'} Dictionary After: {'name': 'Prakash', 'age': 35, 'city': 'Delhi', 'occupation': 'Engineer'}
In the above example, we first change the value associated with the key “age” to 35
. Then, we add a new key-value pair, “occupation”: “Engineer”, to the dictionary.
Adding items in Python dictionary
To add items to a Python dictionary, you can simply assign a value to a new key or use the update()
method to add multiple items at once. Here’s how you can do it:
Using assignment
You can add a new key-value pair to a dictionary by assigning a value to a new key:
### Adding item in dictionary Using assignment. # Original dictionary my_dict = {"name": "John", "age": 30} # Adding a new key-value pair my_dict["city"] = "New York" print(my_dict) # Output {'name': 'John', 'age': 30, 'city': 'New York'}
Using update()
method
You can use the update()
method to add multiple items at once by providing another dictionary containing the items to be added:
my_dict = {"name": "John"} print("my_dict before: ",my_dict) # Add multiple items at once. my_dict.update({"age": 30, "city": "New York"}) print("my_dict after update: ",my_dict) # Output my_dict before: {'name': 'John'} my_dict after update: {'name': 'John', 'age': 30, 'city': 'New York'}
Remove items from Python dictionary
To remove items from a Python dictionary, you can use the del
statement to delete a specific key-value pair, or you can use the pop()
method to remove an item by its key and get its value. Here’s how you can do it:
Using the del
Statement:
You can remove a specific key-value pair from a dictionary using the del
statement:
person = {"name": "Shivaay", "location": "Delhi", "age": 6} print("person before: ", person) del person["age"] print("person after: ", person) # Output person before: {'name': 'Shivaay', 'location': 'Delhi', 'age': 6} person after: {'name': 'Shivaay', 'location': 'Delhi'}
In the above example, the key "age"
and its corresponding value 6 are removed from the dictionary.
Using the del
Statement to delete entire dictionary
The del
keyword can also delete the dictionary completely:
person = {"name": "Shivaay", "location": "Delhi", "age": 6} print("person before: ", person) del person print("person after: ", person) # Output NameError: name 'person' is not defined
The above example will throw ERROR because person
dictionary does not exist.
Using clear()
method
You can also clear the dictionary using clear()
method. This deletes all elements in the dictionary.
person = {"name": "Shivaay", "location": "Delhi", "age": 6} print("person before: ", person) person.clear() print("person after: ", person) # Output person before: {'name': 'Shivaay', 'location': 'Delhi', 'age': 6} person after: {}
Using the pop()
Method:
You can use the pop()
method to remove an item by its key and get its value at the same time:
my_dict = {"name": "John", "age": 30, "city": "New York"} print("my_dict before: ", my_dict) # Removing a key-value pair using pop removed_value = my_dict.pop("age") print("Removed Value:", removed_value) # Output: Removed Value: 30 print("my_dict after: ", my_dict) # Output my_dict before: {'name': 'John', 'age': 30, 'city': 'New York'} Removed Value: 30 my_dict after: {'name': 'John', 'city': 'New York'}
In this example, the key "age"
and its corresponding value 30
are removed from the dictionary, and the value 30
is assigned to the variable removed_value
.
Loop over Python dictionary
Looping over a Python dictionary allows you to iterate through its key-value pairs. There are several ways to iterate over a dictionary in Python, depending on whether you want to iterate over keys, values, or both. Here are the common methods:
Looping Over Keys:
You can iterate over the keys of a dictionary using a for
loop:
person = { "name": "Prakash", "age": 35, "city": "New Delhi" } for key in person: print("key: ", key) # Output key: name key: age key: city for key in person.keys(): print("key: ", key) # Output key: name key: age key: city
Looping Over Values:
You can iterate over the values of a dictionary using the values()
method:
person = { "name": "Prakash", "age": 35, "city": "New Delhi" } for value in person.values(): print("Value: ", value) # Output Value: Prakash Value: 35 Value: New Delhi
Looping Over Key-Value Pairs:
You can iterate over the key-value pairs of a dictionary using the items()
method:
person = { "name": "Prakash", "age": 35, "city": "New Delhi" } for key, value in person.items(): print("Key: ", key, " Value: ", value) # Output Key: name Value: Prakash Key: age Value: 35 Key: city Value: New Delhi
Copy a dictionary in Python
In Python, you can create a copy of a dictionary using various methods. Here are some common approaches to copy a dictionary:
Using the copy()
Method:
You can use the copy()
method to create a shallow copy of the dictionary:
# Original dictionary my_dict = {"name": "Proedu.co", "age": 6, "city": "New Delhi"} # Creating a shallow copy using the copy() method copied_dict = my_dict.copy() # Modifying the original dictionary my_dict["name"] = "Shivaay" print("Original Dictionary:", my_dict) print("Copied Dictionary:", copied_dict) # Output Original Dictionary: {'name': 'Shivaay', 'age': 6, 'city': 'New Delhi'} Copied Dictionary: {'name': 'Proedu.co', 'age': 6, 'city': 'New Delhi'}
Using the dict()
Constructor:
You can use the dict()
constructor with the original dictionary as an argument to create a copy. This approach also creates a shallow copy of the dictionary.
my_dict = {"name": "Proedu.co", "age": 6, "city": "New Delhi"} copied_dict = dict(my_dict) print("Original Dictionary:", my_dict) print("Copied Dictionary:", copied_dict) # Output Original Dictionary: {'name': 'Proedu.co', 'age': 6, 'city': 'New Delhi'} Copied Dictionary: {'name': 'Proedu.co', 'age': 6, 'city': 'New Delhi'}
Using Dictionary Comprehension:
You can use dictionary comprehension to create a copy of the dictionary. This approach is similar to using the dict()
constructor.
my_dict = {"name": "Proedu.co", "age": 6, "city": "New Delhi"} copied_dict = {key: value for key, value in my_dict.items()} print("Original Dictionary:", my_dict) print("Copied Dictionary:", copied_dict) # Output Original Dictionary: {'name': 'Proedu.co', 'age': 6, 'city': 'New Delhi'} Copied Dictionary: {'name': 'Proedu.co', 'age': 6, 'city': 'New Delhi'}
Using copy.deepcopy()
for Deep Copy:
If your dictionary contains nested objects and you need to create a deep copy (i.e., copy the nested objects as well), you can use the copy.deepcopy()
function from the copy
module:
import copy my_dict = {"name": "Proedu.co", "age": 6, "city": "New Delhi"} copied_dict = copy.deepcopy(my_dict) print("Original Dictionary:", my_dict) print("Copied Dictionary:", copied_dict) # Output Original Dictionary: {'name': 'Proedu.co', 'age': 6, 'city': 'New Delhi'} Copied Dictionary: {'name': 'Proedu.co', 'age': 6, 'city': 'New Delhi'}
Nested dictionary in Python
In Python, a nested dictionary is a dictionary that contains another dictionary (or dictionaries) as its values. This allows you to represent hierarchical data structures where each level of the hierarchy is represented by a separate dictionary. Here’s an example of a nested dictionary.
nested_dict = { "person1": { "name": "Shivaay", "age": 6 }, "person2": { "name": "Proedu.co", "age": 5 } } # Accessing nested dictionary values print("Person1 Name: ", nested_dict["person1"]["name"]) print("Person2 Age: ", nested_dict["person2"]["age"]) # Output Person1 Name: Shivaay Person2 Age: 5
In this example, nested_dict
contains two key-value pairs where each value is another dictionary representing information about a person. You can access the nested dictionaries and their values using multiple levels of indexing.
You can also modify, add, or delete values within the nested dictionaries just like you would with any other dictionary.
nested_dict = { "person1": { "name": "Shivaay", "age": 6 }, "person2": { "name": "Proedu.co", "age": 5 } } # Modifying age of Person1. nested_dict["person1"]["age"] = 7 # Adding a new key-value pair to a nested dictionary nested_dict["person2"]["gender"] = "Male" # Deleting a key-value pair from a nested dictionary del nested_dict["person1"]["age"] print(nested_dict) # Output {'person1': {'name': 'Shivaay'}, 'person2': {'name': 'Proedu.co', 'age': 5, 'gender': 'Male'}}
Python Dictionary fromkeys()
method
The fromkeys()
method in Python dictionary is used to create a new dictionary with specified keys and optional default values. This method generates a dictionary where each key is taken from an iterable (like a list or tuple) and each key is associated with the same default value, which can be optionally specified.
Here’s the syntax of the fromkeys()
method:
dictionary.fromkeys(iterable, value)
iterable
: The iterable (e.g., list, tuple, etc.) containing keys that will be used to create the dictionary.value
(optional): The default value to associate with each key. If not provided, the default value will beNone
.
# Example1: Creating a dictionary with default values using fromkeys() keys = ["name", "age", "city"] default_value = "Unknown" person = dict.fromkeys(keys, default_value) print(person) # Example2: Creating a dictionary with default values using fromkeys() keys = ["name", "age", "city"] person = dict.fromkeys(keys) print(person) # Output {'name': 'Unknown', 'age': 'Unknown', 'city': 'Unknown'} {'name': None, 'age': None, 'city': None}
In this example, the fromkeys()
method creates a new dictionary my_dict
with keys taken from the keys
list and each key is associated with the default value "Unknown"
. If you don’t specify the default value, it defaults to None
.
This method is useful when you want to initialize a dictionary with default values for a given set of keys. It’s particularly handy when you’re setting up a dictionary where you expect to fill in values later, or when you want to initialize a dictionary for use as a counter or lookup table.
Python Dictionary setdefault()
Method
The setdefault()
method in Python dictionary is used to retrieve the value of a specified key in the dictionary. If the key does not exist, it inserts the key with a specified value (defaulting to None
if not provided) into the dictionary.
Here’s the syntax of the setdefault()
method:
dictionary.setdefault(key, default_value)
key
: The key to search for in the dictionary.default_value
(optional): The value to be inserted into the dictionary if the key is not found. If not provided, the default value will beNone
.
person = {"age": "6"} # Using setdefault to add a new key-value pair. name = person.setdefault("name", "Shivaay") print("Person: ", person) print("name: ", name) # Using setdefault to retrieve value for an existing key. age = person.setdefault("age",7) print("age: ", age) # Using setdefault() to add a key with a default value. city = person.setdefault("city") print("city: ", city) print("Person: ", person) # Output Person: {'age': '6', 'name': 'Shivaay'} name: Shivaay age: 6 city: None Person: {'age': '6', 'name': 'Shivaay', 'city': None}