Python Dictionary is a collection of Key value pairs. i.e., An element is a key & a value pair. The key is a unique value for which a value will be associated. The element’s value part can be retrieved using the key part.
Key must be a unique value but values can be duplicated.
Mutability:
- A dictionary is a mutable objects and its elements also is mutable by using the key part.
- Access an item using the key.
- Add items directly by dict_name[new_key_name] = new_value
- Remove any values using pop or popitem
- pop – takes in a key value as argument and removes that item. So you can remove any item regardless of its position.
- popitem – no arguments. Simply removes the last item.
Syntax:
variable_name = {key1: value1, key2: value2, ......, keyN: valueN}
Example:
Syntax to access an element: dictionary_name[key]
dict1={'a':'test', 1:'second', 3: 'last'}
print(dict1)
print("Access an element of key 'a':", dict1["a"])
{'a': 'new', 1: 'second', 3: 'last'} Access an element of key 'a': new
What happens if a key is duplicated?
dict1={'a':'test', 1:'second', 'a':'new', 3: 'last'}
print(dict1)
{'a': 'new', 1: 'second', 3: 'last'}
In the above example, the key ‘a’ is duplicated. When a key is duplicated, the first occurrence value will be overridden by the last occurrence’s value.
Pop function:
Pop function takes an mandatory argument as a key value. It removes the pair from dictionary and returns the value part.
dict1={1:'First', 2:'Second', 3: 'Last'}
print("Original Dictionary: ",dict1)
print("Value of key '1'", dict1.pop(1))
print("After pop:", dict1)
Original Dictionary: {1: 'First', 2: 'Second', 3: 'Last'} Value of key '1' First After pop: {2: 'Second', 3: 'Last'}
We have seen how to change the value part. But how to change the key part of a pair?
There is no direct method. However there is a workaround.
The pop function removes the pair and returns the value. We can use this return value and add a new element with a new name. As there is no way to access using the index of an element in Dictionary, the order does not matter.
dict1={1:'First', 2:'Second', 3: 'Last'}
print("Before changes: ",dict1)
dict1["changed"] = dict1.pop(1)
print("After changes:", dict1)
Before changes: {1: 'First', 2: 'Second', 3: 'Last'} After changes: {2: 'Second', 3: 'Last', 'changed': 'First'}
Popitem function:
Popitem function removes and returns an element in random choice. The returned value is a size 2 Tuple containing the key and value parts.
dict1={1:'First', 2:'Second', 3: 'Last'}
print("Before changes: ",dict1)
removed = dict1.popitem()
print("Popitem result:", removed)
print("Type of return value:", type(removed))
print("After changes:", dict1)
Before changes: {1: 'First', 2: 'Second', 3: 'Last'} Popitem result: (3, 'Last') Type of return value: <class 'tuple'> After changes: {1: 'First', 2: 'Second'}