- Python dictionary is an unordered collection of items.
- While lists tuples have only value as an element, a dictionary has a ‘key’:’value’ pair.
- Dictionaries are optimised to retrieve values when the key is known.
- An element has a key and the corresponding value expressed as a pair, key: value.
- While values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique.
- Key and value pairs can be of any type.
- In Python, dictionaries are defined within braces {} with each item being a pair in the form key:value.
d = {‘fruit1′:’apple’, ‘fruit2′:’banana’, ‘rate_apple’: 100, ‘rate_banana’: 40}
print(d)
d = {}
# dictionary with integer keys
d = {1: ‘apple’, 2: ‘banana’}
# dictionary with mixed keys
d = {‘name’: ‘eddy’, 1: [2, 4, 3]}
# using dict()
d = dict({1:’apple’, 2:’banana’})
# from sequence having each item as a pair
d = dict([(1,’apple’), (2,’banana’)])
- We use key to retrieve the respective value not slicing as shown below.
print(d['fruit1'])
print(d['rate_apple'])
print(d['banana']) ### This will result in error as we cannot use values
How to access elements from a dictionary?
- While indexing is used with other container types to access values, dictionary uses keys.
- Key can be used either inside square brackets or with the get() method.
- The difference while using get() is that it returns None instead of KeyError, if the key is not found.
d = {‘name’:’Eddy’, ‘age’: 32}
print(d.get(‘age’)) # Output: 32
How to change or add elements in a dictionary?
- Python dictionaries are mutable in nature.
- We can add new items or change the value of existing items using assignment operator.
- If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.
d = {‘name’:’Eddy’, ‘age’: 32}
d[‘age’] = 33 # update value
print(d) #Output: {‘age’: 33, ‘name’: ‘Eddy’}
d[‘address’] = ‘India’ # add item
print(d) # Output: {‘address’: ‘India’, ‘age’: 33, ‘name’: ‘Eddy’}
How to delete or remove elements from a dictionary?
- We can remove a particular item in a dictionary by using the pop() method.
- This method removes as item with the provided key and returns the value.
- The method, popitem() can be used to remove and return an arbitrary item (key, value) form the dictionary.
- All the items can be removed at once using the clear()method.
- We can also use the del keyword to remove individual items or the entire dictionary itself.
square = {1:1, 2:4, 3:9, 4:16, 5:25}
print(square.pop(4)) # Remove a particular item # Output: 16
print(square) # Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(square.popitem()) # Remove an arbitrary item. # Output: (1, 1)
print(square) # Output: {2: 4, 3: 9, 5: 25}
del square[5] # Delete a particular item
print(square) # Output: {2: 4, 3: 9}
square.clear() # Remove all items
print(square) # Output: {}
del square # Delete the dictionary itself
Python Dictionary Methods:
Python Dictionary Comprehension:
- Dictionary comprehension is an elegant and concise way to create new dictionary from an iterable in Python.
- Dictionary comprehension consists of an expression pair (key: value) followed by for statement inside curly braces {}.
- Here is an example to make a dictionary with each item being a pair of a number and its square.
square = {x: x*x for x in range(6)}
- A dictionary comprehension can optionally contain more for or if statements.
Other Dictionary Operations:
- Dictionary Membership Test
- We can test if a key is in a dictionary or not using the keyword in.
- Notice that membership test is for keys only, not for values.
square = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(1 in square) # Output: True
print(2 not in square) # Output: True
print(49 in square) # Output: False