[英]Dictionary only adds in the last key value pair in for loop
我有一個 for 循環,它遍歷城市列表並為每個城市分配一個total_city_value
。 我正在嘗試將在 for 循環期間創建的每個唯一的 total_city_value 添加到字典中,但是當我打印字典時,它似乎只是將最終的 total_city_value 保留在 for 循環中。
for broad_variable in broad_variable_list:
# check if the current broad variable is equal to the first broad variable the user chose
if broad_variable == broad_variable1:
# if the city's specific variable is equal to the specific variable the user chose get the value of it based on it's ranking weight
if City.objects.values_list(broad_variable, flat=True).filter(city=cities).first() == specific_variable1:
city_variable1_value = 1 * weight_variable1
#print("city_variable1_value",city_variable1_value)
# else assign a value of 0
else:
city_variable1_value = 0
# check if the current broad variable is equal to the second broad variable the user chose
if broad_variable == broad_variable2:
# if the city's specific variable is equal to the specific variable the user chose get the value of it based on it's ranking weight
if City.objects.values_list(broad_variable, flat=True).filter(city=cities).first() == specific_variable2:
city_variable2_value = 1 * weight_variable2
# else assign a value of 0
else:
city_variable2_value = 0
total_city_value = city_variable1_value + city_variable2_value
city_value_dictionary[cities] = total_city_value
print(city_value_dictionary)
也許它很簡單:
city_value_dictionary[cities] += total_city_value
將新值添加到現有值? 您可能需要檢查這是否是該cities
值的第一次,因為第一次不會添加條目。 一些老生常談的東西:
try:
city_value_dictionary[cities] += total_city_value
except KeyError:
city_value_dictionary[cities] = total_city_value
或者:
total = city_value_dictionary.get(cities, 0)
city_value_dictionary[cities] = total + total_city_value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.