dict
in Python, is an unordered collection of key & value pairs of items. Dictionaries are mutable, iterable, but Indexing/Slicing doesn't work as their order doesn't matter.# Create empty dictionary
my_dict = {}
# or using dict() function
my_dict = dict()
# Initialize with keys & values inside '{}' brackets
my_dict = {"e": 23, "w": 65, "q": 52}
# Note: Key & value are separated with ':' colon. i.e key:value
my_dictionary = {"raf": 23, "soe": 65, "qr": 52, 10: 20}
## Adding values
my_var = 20
key = 10
tuple_key = (20,)
# add item at key, provide key in '[]' brackets
# if the key is already present, the previous value will be replaced
# For example, adding key=10 and value=20
my_dictionary[key] = my_var
# Another example, adding key=(20,) & value=45 and key='az' & value=42
my_dictionary[tuple_key] = 45
my_dictionary["az"] = 42
print(my_dictionary) # {'raf': 23, 'soe': 65, \
# 'qr': 52, 10: 20, (20,): 45, 'az': 42}
## Removing values
del my_dictionary[tuple_key]
print(my_dictionary) # {'raf': 23, 'soe': 65, \
# 'qr': 52, 10: 20, 'az': 42}
## Accessing elements
key = "qr"
my_var = my_dictionary[key] # can raise 'KeyError' if not present
# use 'get()' method to avoid 'KeyError', 'None' is a default alternative
# which will be returned when key is not present, can be set to anything else
print(my_dictionary.get("ar", None)) # None
## Check if key is inside 'my_dictionary'
if "az" in my_dictionary:
print("printed") # printed
my_dictionary = {'a':34, 'b': 42}
my_dictionary1 = {'z':5, 'y':3, 'x':4}
## Joining: Join two dictionary, '+' operator is not supported
# using the update method of dictionary
my_dictionary.update(my_dictionary1)
print(my_dictionary) # {'a': 34, 'b': 42, 'z': 5, 'y': 3, 'x': 4}
# or using pipe like this "my_dictionary | my_dictionary1"
print(my_dictionary | my_dictionary1) # {'a': 34, 'b': 42, \
# 'z': 5, 'y': 3, 'x': 4}
# or unpack them in a new dictionary
print({**my_dictionary, **my_dictionary1}) # {'a': 34, 'b': 42, \
# 'z': 5, 'y': 3, 'x': 4}
## Iterating: Going over item by item from a dictionary
# use the items method for both keys, values unpacking
for k,v in my_dictionary1.items():
print(k, v) # {'z':5, 'y':3, 'x':4}
my_dictionary = {x:x*x for x in range(5)} # generating keys and values on the go
print(my_dictionary) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# another way is using the zip function
my_keys = ['a', 'b', 'c']
my_values = [1,2,3]
my_dictionary = {k:v for k,v in zip(my_keys, my_values)}
print(my_dictionary) # {'a': 1, 'b': 2, 'c': 3}
# similar to list's comprehension, dictionaries also support if or
# if..else clause
# inside comprehension, create a dictionary without a key 'a'
my_dictionary = {k:v for k,v in zip(my_keys, my_values) if k != 'a' }
print(my_dictionary) # {'b': 2, 'c': 3}
my_dictionary = {"a": 1, "b": 2, "c": 3}
# Returns a 'dict_keys' object, it contains dictionary's keys,
# it is iterable and can be converted to 'list'
print(my_dictionary.keys()) # dict_keys(['a', 'b', 'c'])
print(list(my_dictionary.keys())) # ['a', 'b', 'c']
# Returns a 'dict_values' object, it contains dictionary's values,
# similarly it is iterable and can be converted to 'list'
print(my_dictionary.values()) # dict_values([1, 2, 3])
# Returns a 'dict_items' object, has keys & values, you know the rest
print(my_dictionary.items()) # dict_items([('a', 1), ('b', 2), ('c', 3)])
# Removes item(key,value) given key, which is 'a' here and returns value
print(my_dictionary.pop("a")) # 1
# Removes all items from dictionary
my_dictionary.clear()
keys = [1, 2]
values = [2, 3]
my_dict = dict([keys, values]) # list to dictionary
my_dict = dict(((1, 2), (2, 3))) # tuple to dictionary
Time Complexity