Simmen
Simmen

Reputation: 93

How to overwrite values in a Python dictonary?

I have this example:

    d = {}
    x = {'key1': 'value1', 'key2': 'value2'}
    above = ['abovekey1', 'abovekey2']

    for ak in above:
        d[ak] = x
        d[ak]['key2'] = str(ak)

The output of d is:

{'abovekey1': {'key1': 'value1', 'key2': 'abovekey2'},
 'abovekey2': {'key1': 'value1', 'key2': 'abovekey2'}}

But I wrote the code to expect this output:

{'abovekey1': {'key1': 'value1', 'key2': 'abovekey1'},
 'abovekey2': {'key1': 'value1', 'key2': 'abovekey2'}}

How can I change the code to yield the output that I am expecting and what am I missing in the above example?

Thank you all!

Upvotes: 1

Views: 76

Answers (3)

buddemat
buddemat

Reputation: 5301

In python, objects are never implicitly copied but instead referenced. If you want to edit a separate dictionary, you need to copy it first.

Beware: the .copy() operation makes a shallow copy of a dictionary. If your dictionary has more hierarchy levels/nested dicts and you want to copy all of them, you need to make a deep copy using .deepcopy(). For this you need to import it first

from copy import deepcopy

See https://docs.python.org/3/library/copy.html for more info on shallow vs. deep copy.

Upvotes: 0

Rakesh
Rakesh

Reputation: 82765

You need to make a copy of x use .copy

Ex:

d = {}
x = {'key1': 'value1', 'key2': 'value2'}
above = ['abovekey1', 'abovekey2']

for ak in above:
    d[ak] = x.copy()
    d[ak]['key2'] = ak
    
print(d)

Output:

{'abovekey1': {'key1': 'value1', 'key2': 'abovekey1'},
 'abovekey2': {'key1': 'value1', 'key2': 'abovekey2'}}

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195428

As stated in the comments, d[ak] = x references the same dictionary. You can achieve desired result by making a copy of x:

x = {'key1': 'value1', 'key2': 'value2'}
above = ['abovekey1', 'abovekey2']

d = {k: dict(x, key2=k)  for k in above}
print(d)

Prints:

{'abovekey1': {'key1': 'value1', 'key2': 'abovekey1'}, 'abovekey2': {'key1': 'value1', 'key2': 'abovekey2'}}

Upvotes: 1

Related Questions