Dictionaries
Dictionaries
A dictionary in Python is a built-in data type that stores collections of key-value pairs.
Dictionaries are also known as associative arrays or hash maps. They are unordered, mutable,
and indexed by keys, which can be of any immutable data type (such as strings, numbers, or
tuples).
Creating a Dictionary
Accessing Values
value = my_dict["key1"]
If you try to access a key that does not exist, a KeyError will be raised. To avoid this, use the
get() method, which returns None or a default value if the key is not found:
You can add a new key-value pair or modify an existing one by using the assignment
operator:
Removing Entries
del my_dict["key1"]
2. Using the pop() method, which returns the removed value:
value = my_dict.pop("key2")
3. Using the popitem() method to remove and return an arbitrary key-value pair
(in Python 3.7+ it removes the last item):
my_dict.clear()
Dictionary Methods
keys = my_dict.keys()
values = my_dict.values()
items = my_dict.items()
update(): Updates the dictionary with key-value pairs from another dictionary or an
iterable of key-value pairs.
my_dict.update({"key4": "value4"})
Dictionary Comprehensions
Similar to list comprehensions, you can create dictionaries using dictionary comprehensions:
python
squares = {x: x*x for x in range(6)}
Nested Dictionaries
Dictionaries can contain other dictionaries, which allows you to create nested structures:
# or
fruit_colors = {
"apple": "red",
"banana": "yellow",
"cherry": "red",
"grape": "purple"
print("Initial dictionary:")
print("fruit_colors:", fruit_colors)
# Accessing values
print("\nAccessing values:")
print("fruit_colors:", fruit_colors)
# Removing entries
print("fruit_colors:", fruit_colors)
print("fruit_colors:", fruit_colors)
print("fruit_colors:", fruit_colors)
# Dictionary methods
print("\nDictionary methods:")
print("Keys:", fruit_colors.keys())
print("Values:", fruit_colors.values())
print("Items:", fruit_colors.items())
# Updating a dictionary
print("fruit_colors:", fruit_colors)
# Dictionary comprehension
print("fruit_lengths:", fruit_lengths)
# Nested dictionaries
fruit_properties = {
print("\nNested dictionary:")
print("fruit_properties:", fruit_properties)
# Counting occurrences
fruit_count = {}
if fruit in fruit_count:
fruit_count[fruit] += 1
else:
fruit_count[fruit] = 1
print("fruit_count:", fruit_count)
Output:
Initial dictionary:
fruit_colors: {'apple': 'red', 'banana': 'yellow', 'cherry': 'red', 'grape': 'purple'}
Accessing values:
Color of apple: red
Color of banana: yellow
Color of cherry (with default): red
Dictionary methods:
Keys: dict_keys(['apple', 'banana', 'cherry'])
Values: dict_values(['red', 'yellow', 'red'])
Items: dict_items([('apple', 'red'), ('banana', 'yellow'), ('cherry', 'red')])
Nested dictionary:
fruit_properties: {'apple': {'color': 'red', 'taste': 'sweet'}, 'banana': {'color': 'yellow', 'taste':
'sweet'}, 'grape': {'color': 'purple', 'taste': 'sweet or sour'}}