Python dictionaries are unordered collections of items. Each item of a dictionary has a key/value pair. Dictionaries are optimised to retrieve values when the key is known.
a. Creating a dictionary: Dictionaries in Python can be created by placing items inside curly braces { } separated by commas.
Code
my_dict = {'name': 'John', 'age': 30}
print(my_dict)
Output
{'name': 'John', 'age': 30}
b. Accessing elements from a dictionary: While indexing is used with other data types to access values, a dictionary uses keys. Keys can be used either inside square brackets [ ] or with the get() method.
Code
my_dict = {'name': 'John', 'age': 30}
print(my_dict['name'])
print(my_dict.get('age'))
Output
c. Modifying and adding key-value pairs in dictionary: Dictionaries are mutable. We can add new items or change the value of existing items using an assignment operator. If the key is already present, then the existing value gets updated. In case the key is not present, a new key: value pair is added to the dictionary.
Code
my_dict = {'name': 'John', 'age': 30}
my_dict['age'] = 40
my_dict['address'] = 'Downtown'
print(my_dict)
Output
{'name': 'John', 'age': 40, 'address': 'Downtown'}
d. Removing elements from a dictionary: We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value.
Code
my_dict = {'name': 'John', 'age': 30, 'address': 'Downtown'}
removed_value = my_dict.pop('address')
print(my_dict)
print('Removed Value: '+ removed_value)
Output
{'name': 'John', 'age': 30}
Removed Value: Downtown
e. Dictionary Methods: Python includes the following built-in methods to manipulate dictionaries - clear(), copy(), fromkeys(), get(), items(), keys(), pop(), popitem(), setdefault(), update(), values().
Code
my_dict = {'name': 'John', 'age': 30, 'address': 'Downtown'}
print(my_dict.keys())
print(my_dict.values())
print(my_dict.items())
print(my_dict.get('name'))
Output
dict_keys(['name', 'age', 'address'])
dict_values(['John', 30, 'Downtown'])
dict_items([('name', 'John'), ('age', 30), ('address', 'Downtown')])
John
Enquiries
[email protected]
Copyright © 2023 - slash-root.com