Skip to content

Creating a dictionary:

# This creates a dictionary with keys 'a' and 'b' and values 1 and 2
my_dict = {'a': 1, 'b': 2}

# This creates an empty dictionary
empty_dict = {}

Accessing elements of a dictionary:

# This will print the value for key 'a'
print(my_dict['a'])

# This will print the value for key 'b'
print(my_dict.get('b'))

# This will print all the keys in the dictionary
print(my_dict.keys())

# This will print all the values in the dictionary
print(my_dict.values())

Modifying elements of a dictionary:

# This will add a new key-value pair to the dictionary
my_dict['c'] = 3

# This will update the value for key 'b'
my_dict['b'] = 4

# This will remove the key-value pair for key 'a'
del my_dict['a']

Iterating over a dictionary:

# This will print all the key-value pairs in the dictionary
for key, value in my_dict.items():
print(f"{key}: {value}")

# This will print all the keys in the dictionary
for key in my_dict:
print(key)

# This will print all the values in the dictionary
for value in my_dict.values():
print(value)

Using the sorted function:

# This will create a new list with the keys of the dictionary sorted in ascending order
sorted_keys = sorted(my_dict)

# This will create a new list with the values of the dictionary sorted in ascending order
sorted_values = sorted(my_dict.values())

Using the items function:

# This will create a new list with the key-value pairs in the dictionary as tuples
items = list(my_dict.items())

Using defaultdict:

from collections import defaultdict

# This will create a defaultdict with a default value of 0
my_defaultdict = defaultdict(int)

# This will increment the value for key 'a' by 1
my_defaultdict['a'] += 1

# This will print 1
print(my_defaultdict['a'])

# This will print 0, because 'b' has not been set yet
print(my_defaultdict['b'])

Using Counter:

from collections import Counter

# This will create a Counter from a list of elements
my_counter = Counter(['a', 'b', 'c', 'a', 'b'])

# This will print the count for each element
print(my_counter)

# This will print the most common elements and their counts
print(my_counter.most_common())

Merging dictionaries:

# This will create a new dictionary with the key-value pairs from both dictionaries
merged_dict = {**dict1, **dict2}

# This will create a new dictionary with the key-value pairs from both dictionaries,
# using the update method
merged_dict = {}
merged_dict.update(dict1)
merged_dict.update(dict2)

Using a dictionary to store data in a matrix form:

# This creates a dictionary with keys (i, j) and values 0, for all i and j in the range 1 to 3
matrix = {(i, j): 0 for i in range(1, 4) for j in range(1, 4)}

# This will set the value at position (2, 3) to 5
matrix[(2, 3)] = 5

# This will print the value at position (2, 3)
print(matrix[(2, 3)])

# This will print the entire matrix
print(matrix)