Hi I simplified my weirdly behaving code as far as i could:
def GH():
house = {}
weather = {1: 15.6, 2: 16.7, 3: 17.8}
data = {}
for hour in range(1,4):
house["Temperature"] = weather[hour]
data[hour] = [house, weather[hour]]
for key in data:
print(key, data[key])
print("#############################")
return data
x = GH()
its result is:
1 [{'Temperature': 15.6}, 15.6]
#############################
1 [{'Temperature': 16.7}, 15.6]
2 [{'Temperature': 16.7}, 16.7]
#############################
1 [{'Temperature': 17.8}, 15.6]
2 [{'Temperature': 17.8}, 16.7]
3 [{'Temperature': 17.8}, 17.8]
#############################
The "hour" from the for loop is the key of the dictionary. In every cycle it adds a new element to the dictionary, however, it overwrites every earlier element as well which are not addressed. I am not able to understand why the last value of "weather" updates every single "Temperature" in the "data" dictionary... Should not do that. Many thanks for the help.
EDIT: expected output:
1 [{'Temperature': 15.6}, 15.6]
#############################
1 [{'Temperature': 15.6}, 15.6]
2 [{'Temperature': 16.7}, 16.7]
#############################
1 [{'Temperature': 15.6}, 15.6]
2 [{'Temperature': 16.7}, 16.7]
3 [{'Temperature': 17.8}, 17.8]
#############################
CodePudding user response:
You were adding the "same" dictionary to all hours. So when the next iteration changed the dictionary all references to it also changed. To prevent this you just need to "copy" the value from the dictionary:
data[hour] = [house.copy(), weather[hour]]
Code:
def GH():
house = {}
weather = {1: 15.6, 2: 16.7, 3: 17.8}
data = {}
for hour in range(1,4):
house["Temperature"] = weather[hour]
data[hour] = [house.copy(), weather[hour]]
for key in data:
print(key, data[key])
print("#############################")
return data
x = GH()
CodePudding user response:
I assume your expected result is this:
1 [{'Temperature': 15.6}, 15.6]
#############################
1 [{'Temperature': 15.6}, 15.6]
2 [{'Temperature': 16.7}, 16.7]
#############################
1 [{'Temperature': 15.6}, 15.6]
2 [{'Temperature': 16.7}, 16.7]
3 [{'Temperature': 17.8}, 17.8]
#############################
the only problem you have is that when changing the value of house["Temperature"]
, this changes that value for all occurrences where it may appear. So when printing out the dictionary data, in data[key]
, which effectively prints {"Temperature": house["Temperature"]}, weather[hour]
the house["Temperature"] value gets changed every iteration, from 15.6 to 16.7 to 17.8, so it prints those same values for house["Temperature"] every time