Python Dictionaries

Python dictionaries are incredibly versatile and are used extensively in data manipulation and software development. In this guide, we’ll explore the essential aspects of Python dictionaries, providing clear examples to enhance your understanding and skills.

1. Accessing Items

To access the value for a specific key in a dictionary, you use the square brackets [] or the get() method.


my_dict = {'name': 'Alice', 'age': 30}
print(my_dict['name'])  # Output: Alice
print(my_dict.get('age'))  # Output: 30

2. Adding Items

Adding new items to a dictionary is straightforward. You can do this by using a new index key and assigning a value to it.


my_dict['email'] = ''
print(my_dict)  # Output: {'name': 'Alice', 'age': 30, 'email': ''}

3. Changing Items

To change an item, simply assign a new value to an existing key.


my_dict['age'] = 32
print(my_dict)  # Output: {'name': 'Alice', 'age': 32, 'email': ''}

4. Removing Items

Items can be removed from a dictionary using the pop() method, del keyword, or the popitem() method which removes the last inserted item.


del my_dict['age']
print(my_dict)  # Output: {'name': 'Alice'}

5. Looping through Dictionaries

You can loop through a dictionary by using a for loop.


for key in my_dict:
    print(key, my_dict[key])  # Output: name Alice

6. Copying Dictionaries

Use the copy() method or the dict() function to make a copy of a dictionary.


my_dict_copy = my_dict.copy()
print(my_dict_copy)  # Output: {'name': 'Alice'}

7. Nested Dictionaries

A dictionary can contain multiple dictionaries, this is known as nested dictionaries.


family = {
    "child1" : {"name" : "Emil", "year" : 2004},
    "child2" : {"name" : "Tobias", "year" : 2007},
    "child3" : {"name" : "Linus", "year" : 2011}
print(family['child2'])  # Output: {'name': 'Tobias', 'year': 2007}

By mastering these fundamental aspects of Python dictionaries, you’ll be well-equipped to handle various data manipulation tasks with ease. Remember, practice is key to becoming proficient in Python, so try out these examples and experiment with them to deepen your understanding.