There are two dictionaries: a
and b
. b
is created using a
, but it does not point to the same object as a
. (a is b
returns False
)
I have observed that when I update a value in b
: it changes the corresponding value of a
(not by the same update that happened in b
though). What's more troubling is that, this is only observed when using the tf.keras.optimizers.get
function to update b
. When used some other method to update b
, this behavior is not observed.
Also, the change applied to a b
's element isn't applied to a
's corresponding element, but rather an augmentation of a
's corresponding element is resulted - a lower cased dictionary value, while no lowercase()
function was applied.
Reproducible example:
import tensorflow as tf
a = {
"x": 1,
'y': {
'class_name': 'Adam',
'config': {
'learning_rate': 0.0001
}
}
} # a['y'] can be passed as an input to tf.keras.optimizers.get
b = {key: value for key, value in a.items()}
print(a) # b also looks the same
# {'x': 1,
# 'y': {'class_name': 'Adam', 'config': {'learning_rate': 0.0001}}}
Update the 'y'
value of b
:
b['y'] = tf.keras.optimizers.get(b['y'])
As expected, b
is changed:
print(b)
# {'x': 1,
# 'y': <tensorflow.python.keras.optimizer_v2.adam.Adam at 0x7f5656476090>}
But, this has also changed the value of a['y']['class_name']
to lower case!
print(a)
# {'x': 1,
# 'y': {'class_name': 'adam', 'config': {'learning_rate': 0.0001}}}
But no change is observed in a
when b['x']
is updated like below:
b['x'] = b['x'] * 2
print(a)
# {'x': 1,
# 'y': {'class_name': 'adam', 'config': {'learning_rate': 0.0001}}}
print(b)
# {'x': 2,
'y': <tensorflow.python.keras.optimizer_v2.adam.Adam at 0x7f44374ad610>}
Why is it so? How to avoid it?
Edit 1:
After comments about shallow copy:
a['x'] is b['x'], a['y'] is b['y']
# (True, True) # Edit 1.1 - executed just after the definitions of a and b
Edit 2:
Regarding the Close vote:
I do not understand why a['y']['class_name']
went from 'Adam'
to 'adam'
(lower case). This is not discussed in the suggested duplicate.
No lowercase()
function was applied to any of the elements in either dictionary.