0
dictOne = {'a':1, 'b':2}
dictTwo = {'aa':dictOne['a'], 'bb':dictOne['b']}

print(dictTwo['aa']
# returns 1

If I make a change to dictOne like:

dictOne['a'] = 2

print(dictOne['a'])
# returns 2

but the second dict that refers to the first still returns the original value.

print(dictTwo['aa'])
# returns 1

What is happening here? I'm sure this is somehow an inappropriate usage of dict but I need to resolve this in the immediate. Thanks.

micahel
  • 15
  • 5

2 Answers2

0

The line here:

dictTwo = {'aa':dictOne['a'], 'bb':dictOne['b']}

Is equivalent to:

dictTwo = {'aa':1, 'bb':2}

Since dictOne['a'] and dictOne['b'] both return immutable values (integers), they are passed by copy, and not by reference. See How do I pass a variable by reference?

Had you done dictTwo = dictOne, updating dictOne would also update dictTwo, however they would have the same key values.

TheoretiCAL
  • 19,461
  • 8
  • 43
  • 65
0

You're extracting the value from the key 'a' inside dictOne with the below piece of code

dictTwo = {'aa':dictOne['a']}

You may find some value in reading the python FAQ on pass by assignment

Without knowing more about the problem, it's difficult to say exactly how you can solve this. If you need to create a mapping between different sets of keys, there's the option to do something like:

dictTwo = {'aa' : 'a', 'bb' : 'b'}
dictOne[dictTwo['aa']]

Although maybe what you're looking for is a multi key dict

Zooby
  • 325
  • 1
  • 7