Dictionary Operations in Python
This article explains dictionary operations in Python.
You can learn how to define dictionaries, basic operations, how to merge dictionaries, and more, by looking at sample code.
YouTube Video
Dictionary Operations in Python
In Python, a dictionary (dict
) is a collection that manages data as key-value pairs. Unlike lists, you access them by keys, not by position, making lookups and updates efficient.
Definition of a Dictionary
1my_dict = {
2 'apple': 3,
3 'banana': 5,
4 'orange': 2
5}
6print(my_dict)
- A dictionary is written with curly braces
{}
, separating keys and values with a colon:
.
Accessing Keys and Values
1print(my_dict['apple']) # Output: 3
- Specify a key to retrieve its corresponding value.
Adding or Updating Items in a Dictionary
1my_dict['pear'] = 4 # Add a new item
2my_dict['apple'] = 5 # Update an existing item
3print(my_dict)
- You can add a new key-value pair or update the value for an existing key.
Removing Items from a Dictionary
1del my_dict['banana']
2print(my_dict)
- Using
del
deletes the specified key and its value.
1value = my_dict.pop('orange') # Remove the item 'orange' and get its value
2print(value)
3print(my_dict)
- Alternatively, use the
pop
method to remove an item and retrieve its value.
Checking for Key Existence in a Dictionary
1if 'apple' in my_dict:
2 print("Apple is in the dictionary.")
- Use the
in
operator to test whether a key exists in the dictionary.
Iterating Through a Dictionary
1for key, value in my_dict.items():
2 print(f"{key}: {value}")
- Use the
items()
method to loop through the dictionary and process its keys and values. Theitems()
method lets you iterate over both keys and values.
Retrieving Only Keys or Values from a Dictionary
1keys = my_dict.keys()
2values = my_dict.values()
3print(keys)
4print(values)
- Use the
keys()
method to retrieve only the keys or thevalues()
method to retrieve only the values.
Copying a Dictionary
1new_dict = my_dict.copy()
2print(new_dict)
- Use the
copy()
method to create a copy of a dictionary. Thecopy()
method creates a shallow copy. To copy nested dictionaries, you can usecopy.deepcopy()
.
Merging Dictionaries
1dict1 = {'apple': 3, 'banana': 5}
2dict2 = {'orange': 2, 'pear': 4}
3combined_dict = dict1 | dict2
4print(combined_dict)
- From Python 3.9 onwards, the
|
operator can be used as a new way to merge dictionaries.
1dict1.update(dict2)
2print(dict1)
- On older versions, use the
update()
method.
Summary
Dictionaries are a fundamental tool for data management in Python programming. They manage data as key-value pairs and offer many advantages, including fast access, flexible updates, and easy merging. By mastering their use, you will be able to write more efficient and flexible code.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.