Copy a part of a dictionary in Python

avatar

Borislav Hadzhiev

Last updated: Sep 16, 2022

banner

Photo from Unsplash

Copy a part of a dictionary in Python #

To copy a part of a dictionary:

  1. Use a dict comprehension to iterate over the keys to be copied.
  2. On each iteration, return the key and its value.
  3. The new dictionary will only contain the specified keys and values.
main.py
my_dict = { 'id': 1, 'age': 30, 'salary': 100, 'name': 'bobbyhadz', 'language': 'Python' } def copy_part_of_dict(dictionary, keys): return { key: dictionary[key] for key in keys } result = copy_part_of_dict(my_dict, ['name', 'language']) print(result) # 👉️ {'name': 'bobbyhadz', 'language': 'Python'} result = copy_part_of_dict(my_dict, ['name', 'id', 'age']) print(result) # 👉️ {'name': 'bobbyhadz', 'id': 1, 'age': 30}

We used a dict comprehension to iterate over the keys to be copied.

Dict comprehensions are very similar to list comprehensions.

They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.
main.py
my_dict = { 'id': 1, 'age': 30, 'salary': 100, 'name': 'bobbyhadz', 'language': 'Python' } result = {key: my_dict[key] for key in ['name', 'language']} print(result) # 👉️ {'name': 'bobbyhadz', 'language': 'Python'}

An alternative approach is to use the dict() class with tuples of key-value pairs.

main.py
my_dict = { 'id': 1, 'age': 30, 'salary': 100, 'name': 'bobbyhadz', 'language': 'Python' } keys = ['id', 'name', 'language'] result = dict((key, my_dict[key]) for key in keys) print(result) # 👉️ {'id': 1, 'name': 'bobbyhadz', 'language': 'Python'}
We used a generator expression to iterate over the keys and returned a tuple containing 2 elements - the key and the value.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

The dict class can be passed a list of tuples and returns a new dictionary.

You can use a dict comprehension if you need to exclude certain keys from the dictionary.

main.py
my_dict = { 'id': 1, 'age': 30, 'salary': 100, 'name': 'bobbyhadz', 'language': 'Python' } def exclude_keys(dictionary, keys): return { key: value for key, value in dictionary.items() if key not in keys } result = exclude_keys(my_dict, ['id', 'age', 'salary']) print(result) # 👉️ {'name': 'bobbyhadz', 'language': 'Python'}

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

main.py
my_dict = { 'id': 1, 'age': 30, 'salary': 100, 'name': 'bobbyhadz', 'language': 'Python' } # 👇️ dict_items([('id', 1), ('age', 30), ('salary', 100), ('name', 'bobbyhadz'), ('language', 'Python')]) print(my_dict.items())

On each iteration, we use the not in operator to check if the current key is not in the list of keys to exclude.

main.py
def exclude_keys(dictionary, keys): return { key: value for key, value in dictionary.items() if key not in keys }

The in operator tests for membership. For example, x in l evaluates to True if x is a member of l, otherwise it evaluates to False.

x not in l returns the negation of x in l.

The exclude_keys function returns a new dictionary that doesn't contain the specified keys.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.