1

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!

Simmen
  • 93
  • 2
  • 8
  • 1
    You're putting multiple references to `x` inside `d`. If you want them to be different, you want to copy `x` as you put it in `d`. – khelwood Sep 28 '20 at 12:51

3 Answers3

1

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'}}
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

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'}}
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • 1
    Incredible, I would have never ever found the solution. As I am working with nested dicts, I need a deepcopy and found the solution for this here: https://stackoverflow.com/questions/39474959/nested-dictionaries-copy-or-deepcopy – Simmen Sep 28 '20 at 13:00
0

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.

buddemat
  • 4,552
  • 14
  • 29
  • 49