Dictionaries in Python
Dictionaries
Dictionaries are used to store key-value pairs. Key-value pair is like phone numbers with contact name simply, let's understand more:
Creating a Dictionary
To create dictionary, we use curly braces or use dict() function.
# Empty dictionary
my_dict = {}
print(my_dict)
# Dictionary with elements
my_dict = {1: 'Python', 2: 'Java'}
print(my_dict)
# Output:
# {}
# {1: 'Python', 2: 'Java'}
Accessing Elements
You can access elements using keys only. You can either use get() function or just pass the key values and you will be retrieving the values.
my_dict = {'first': 'Python', 'second': 'code'}
# Access using keys
print(my_dict['first'])
# Access elements using get
print(my_dict.get('second'))
# Output:
# Python
# code
Deleting Key-Value Pairs
To delete values, use pop() function which returns value that has been deleted.
my_dict = {1: 'Python', 2: 'Java', 3: 'Ruby'}
# Pop element
a = my_dict.pop('third')
print('Value:', a)
print('Dictionary:', my_dict)
# Pop key-value pair
b = my_dict.popitem()
print('Key, value pair:', b)
print('Dictionary', my_dict)
# Output:
# Value: Ruby
# Dictionary: {1: 'Python', 2: 'Java'}
# Key, value pair: (2, 'Java')
# Dictionary {1: 'Python'}