1

here is my code :

everyday = {'hello':[],'goodbye':{}}
i_want = everyday
i_want ['afternoon'] = 'sun'
i_want['hello'].append((1,2,3,4))
print(everyday)

i would like to obtain this :

i_want = {'afternoon': 'sun', 'hello': [(1, 2, 3, 4)], 'goodbye': {}}

everyday = {'hello':[],'goodbye':{}}

but i obtain :

i_want = {'afternoon': 'sun', 'hello': [(1, 2, 3, 4)], 'goodbye': {}}

everyday = {'afternoon': 'sun', 'hello': [(1, 2, 3, 4)], 'goodbye': {}}

how can i get what i want without modifying the "everyday" dictionary ?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149

3 Answers3

2

Just change this:

everyday = {'hello':[],'goodbye':{}}
i_want = dict(everyday)
i_want ['afternoon'] = 'sun'
i_want['hello'] = []    # We're facing the same issue here and this is why we are initializing a new list and giving it to the hello key
i_want['hello'].append((1,2,3,4))

# to add to goodbye don't forget  the following:
# i_want['goodbye'] = {}
# i_want['goodbye'] = "Some value"

print(everyday)

Whats happening is that calling (i_want = everyday) is actually creating a reference to everyday

For further testing if you would like to see if your dictionaries are referenced simply call

print(i_want is everyday)
marc
  • 914
  • 6
  • 18
0

The following works, similar to marc's answer but instead of creating a new list and then appending, you just do it at the same time the list is created.

everyday = {'hello':[],'goodbye':{}}
print("everyday:", everyday)
i_want = dict(everyday)
i_want ['afternoon'] = 'sun'
i_want['hello'] = [(1, 2, 3, 4)]
print("everyday:", everyday)
print("i_want:", i_want)

Output:

everyday: {'hello': [], 'goodbye': {}}
everyday: {'hello': [], 'goodbye': {}}
i_want: {'hello': [(1, 2, 3, 4)], 'goodbye': {}, 'afternoon': 'sun'}
probat
  • 1,422
  • 3
  • 17
  • 33
-1
everyday = {'hello':[],'goodbye':{}} 
print ('Everyday:',everyday)
i_want = everyday 
i_want ['afternoon'] = 'sun' i_want['hello'].append((1,2,3,4)) 
print(everyday)

Just add the second print statement to get your required output.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
Dev
  • 62
  • 7