Making a dictionary copy

I’m using a copy of a dictionary object so that I have a restore option should the need arise.

The copy does not need to be a full copy, rather it’s a selective copy: any 3 from 5.

Clearly, any ‘copy’ it’s going to be a ‘shallow copy’ and as such, any changes to the one are reflected in the other.

There are a number of ways around this; one of which I’ve posted here:

from copy import deepcopy

# just some simple example data
D1 = {'A': [
    [chr(n) for n in range(65, 91)],
    [chr(n) for n in range(65, 91)]
],
    'B': [
    [chr(n) for n in range(65, 91)],
    [chr(n) for n in range(65, 91)]
],
    'C': [
    [chr(n) for n in range(65, 91)],
    [chr(n) for n in range(65, 91)]
],
    'D': [
    [chr(n) for n in range(65, 91)],
    [chr(n) for n in range(65, 91)]
],
    'E': [
    [chr(n) for n in range(65, 91)],
    [chr(n) for n in range(65, 91)]
]
}

D2_KEYS = ['A', 'B', 'C'] # an example of what may be selected
D2_REMOVE = []
D2 = deepcopy(D1)

for key in D2:
    if key not in D2_KEYS:
        D2_REMOVE.append(key)

for key in D2_REMOVE:
    D2.pop(key)

# the resulting D2 can now be altered or any record restored from D1

Is there a some way to create D2 based on the D2_KEYS, rather than having to remove the unselected items?

With thanks.

Dict comprehension:

D2 = {k: deepcopy(D1[k]) for k in D2_KEYS}
2 Likes

Bang on! Thank you.

I had tried a few different ways, based on list comprehension, but failed.