Dictionaries are one of the fundamental data structures in Python. They are versatile and powerful tools for storing and manipulating data, and they play a crucial role in many Python applications.
In this blog, we’ll explore Python dictionaries in detail, covering their basic syntax, common operations, and some advanced techniques.
What Is a Dictionary?
In Python, a dictionary is a collection of key-value pairs, where each key is unique and maps to a specific value. Dictionaries are unordered, which means that the order of the elements is not guaranteed. They are commonly used to store and retrieve data efficiently, especially when you need fast lookups based on keys.
Creating a Dictionary
You can create a dictionary by enclosing a comma-separated list of key-value pairs within curly braces {}. Each key-value pair is separated by a colon :. Here’s an example of creating a simple dictionary:
my_dict = {"name": "John", "age": 30, "city": "New York"}
In this example, my_dict
is a dictionary with three key-value pairs. The keys are "name", "age",
and "city"
, and the corresponding values are "John", 30
, and "New York"
.
Accessing Values from Dictionary
To access the values in a dictionary, you can use the square brackets [] and provide the key. For example:
name = my_dict["name"]
The name
variable now holds the value "John"
. If the key does not exist in the dictionary, it will raise a KeyError
. To avoid this, you can use the get()
method:
name = my_dict.get("name")
The get()
method returns None
if the key is not found you can specify a default value as the second argument:
name = my_dict.get("name", "Unknown")
Now, if the key "name"
does not exist, name
will be set to "Unknown"
.
Modifying and Adding Elements in Dictionary
Dictionaries are mutable, which means you can modify their contents. To change the value associated with a key, simply assign a new value to that key:
my_dict["age"] = 31
To add a new key-value pair, use the square brackets with a key that doesn’t exist in the dictionary:
my_dict["country"] = "USA"
Now, the dictionary my_dict
has a new key "country"
with the value "USA"
.
Removing Elements from Dictionary
You can remove key-value pairs from a dictionary using the del
statement. For example, to remove the "city"
key and its corresponding value:
del my_dict["city"]
Alternatively, you can use the pop()
method, which not only removes the item but also returns its value:
removed_value = my_dict.pop("city")
Important Dictionary Methods
Python dictionaries come with a variety of built-in methods that allow you to perform common operations:
keys()
:
This method returns a list of all the keys in the dictionary.
my_dict = {"name": "John", "age": 30, "city": "New York"}
keys_list = my_dict.keys()
print(keys_list)
# Output: dict_keys(['name', 'age', 'city'])
values()
:
It returns a list of all the values in the dictionary.
my_dict = {"name": "John", "age": 30, "city": "New York"}
values_list = my_dict.values()
print(values_list)
# Output: dict_values(['John', 30, 'New York'])
items()
:
The items()
method returns a list of key-value pairs as tuples.
my_dict = {"name": "John", "age": 30, "city": "New York"}
items_list = my_dict.items()
print(items_list)
# Output: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])
clear()
:
This method is used to remove all key-value pairs from the dictionary.
my_dict = {"name": "John", "age": 30, "city": "New York"}
my_dict.clear()
print(my_dict)
# Output: {}
copy()
:
This method creates a shallow copy of the dictionary. The shallow copy means, if you change the value from the copied dictionary, then the original dictionary will not update its value. For example,
original_dict = {"name": "John", "age": 30, "city": "New York"}
copied_dict = original_dict.copy()
print(copied_dict)
# Output: {'name': 'John', 'age': 30, 'city': 'New York'}
update()
:
The update method is used to merge the contents of one dictionary into another.
dict1 = {"name": "John", "age": 30}
dict2 = {"city": "New York", "country": "USA"}
dict1.update(dict2)
print(dict1)
# Output: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
Iterating Over Dictionaries
You can loop through the keys, values, or key-value pairs of a dictionary using a for
loop. Here’s how you can iterate over the keys and values:
for key in my_dict:
value = my_dict[key]
print(f"{key}: {value}")
Or, you can use the items()
method to directly iterate over key-value pairs:
for key, value in my_dict.items():
print(f"{key}: {value}")
Dictionary Comprehensions
Just like with lists and sets, you can use dictionary comprehension to create dictionaries in a concise and elegant way. Here’s an example that creates a dictionary of squares:
squares = {x: x**2 for x in range(1, 6)}
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Nested Dictionaries
Dictionaries can be nested within each other to create more complex data structures. This is useful for representing hierarchical or structured data. For instance, you can create a dictionary to represent a person’s information, including contact details:
person = {
"name": "Alice",
"age": 28,
"contact": {
"email": "alice@example.com",
"phone": "123-456-7890"
}
}
You can access nested values using multiple square brackets:
email = person["contact"]["email"]
Merge Dictionaries with |
Python 3.9 introduces the use of the | and |= operators for merging mappings, which is quite intuitive as these operators also serve as set union operators. For example,
my_dict1 = {'a': 1, 'b': 2, }
my_dict2 = {'a': 3, 'b': 4, 'c': 5}
output_dict = my_dict1 | my_dict2
# output_dict = {'a': 3, 'b': 4, 'c': 5}
When you use the | operator, it generates a new mapping. For duplicate keys, later occurrences overwrite previous ones. The value of a is 1 and 3 so later value 3 is saved.
Typically, the type of the resulting mapping aligns with the type of the left operand, like d1 in the given example. However, it may take on the type of the second operand in cases involving user-defined types, in accordance with operator overloading rules.
To update an existing mapping in place, we can use |=. For example, if we want to update my_dict1
my_dict1 = {'a': 1, 'b': 2, }
my_dict2 = {'a': 3, 'b': 4, 'c': 5}
my_dict1 |= my_dict2
# my_dict1 = {'a': 3, 'b': 4, 'c': 5}
Sorting Dictionary by Values
Sorting dictionaries by their values in Python involves creating an ordered representation of the key-value pairs. While dictionaries themselves have no inherent order, we can achieve sorting through functions like sorted().
For example, below is the dictionary of some popular stocks in NSE:
stocks = {
'ITC': 467.55,
'DABUR': 553.75,
'HDFCBANK': 1679.70,
'SBICARD': 768.30,
'TATAPOWER': 358.70
}
# Sorting dictionary
sorted_items = sorted(stocks.items(), key=lambda item: item[1])
This function takes the dictionary’s items() method, yielding tuples for each key-value pair. By specifying a key argument and a lambda function within sorted(), we can tell Python to base the sorting on the values. This essentially extracts the value from each tuple for comparison.
Remember, adding reverse=True to sorted() sorts in descending order. These methods work for dictionaries with various value types, allowing you to easily organize your data based on its values.
# Sort in reverse order
sorted_items = sorted(stocks.items(), key=lambda item: item[1], reverse=True)
Finding Minimum and Maximum Value from Dictionary
Suppose you want to find the minimum and maximum values from a given dictionary key-value pair. Then you can use the zip() method to get these minimum and maximum values.
min_price = min(zip(stocks.values(), stocks.keys())) #(358.7, 'TATAPOWER')
max_price = max(zip(stocks.values(), stocks.keys())) #(1679.7, 'HDFCBANK')
When you’re doing these min and max operations, just remember that when you use zip(), it makes a special list that you can only use one time. For example, the following code shows the error:
prices_and_names = zip(stocks.values(), stocks.keys())
print(min(prices_and_names)) # OK
print(max(prices_and_names)) # ValueError: max() arg is an empty sequence
Discovering Similarities in Two Dictionaries
Suppose you have two dictionaries given below:
x = {
'a': 1,
'b': 2,
'c': 3
}
y = {
'p': 20,
'c': 3,
'r': 30
}
To find common keys in the above two dictionaries:
# Find common in given two dictionaries
x.keys() & y.keys() # {'c'}
If you want to find keys that are in first dictionary x and not in second dictionary y:
# Find keys in x that are not in y
x.keys() - y.keys() # {'a', 'b'}
Finding common key and value pairs in given two dictionaries.
# Find (key,value) pairs in common
x.items() & y.items() # {('c', 3)}
Conclusion
Python dictionaries are a versatile and powerful data structure that can be used for a wide range of applications. They allow you to efficiently store, retrieve, and manipulate data using keys and values. Understanding how to create, access, modify, and iterate over dictionaries is essential for any Python developer. So, whether you’re building a web application, processing data, or just solving coding challenges, dictionaries are a valuable tool to have in your Python toolkit.