为什么Python中的这个字典只存储最后一个输入?

时间:2012-12-22 08:32:21

标签: python dictionary

while (lines < travels + 1):
    data = lines + 1
    startFrom = raw_input ('The package travels from: ')
    startFrom = str(startFrom)
    arriveIn = raw_input ('The package arrives to: ')
    arriveIn = str(arriveIn)
    pack = raw_input('Number of packages: ')
    pack = int(pack)
    print startFrom, '--->', arriveTo, ': ', pack
    capacity = {}
    if capacity.has_key(startFrom):
        capacity[startFrom] = capacity[startFrom] + pack
    else:
        capacity[startFrom] = pack
print capacity

最后它只打印(并且只存储)给定的最后一个输入,不会增加值或将新数据添加到字典中。我也尝试过defaultdic但结果是一样的。

1 个答案:

答案 0 :(得分:3)

您通过循环每次迭代都会将capacity重置为空dict

capacity = {} #Create it before the loop and use this through out the below loop.
while (lines < travels + 1):
 data = lines + 1
 startFrom = raw_input ('The package travels from: ')
 startFrom = str(startFrom)
 arriveIn = raw_input ('The package arrives to: ')
 arriveIn = str(arriveIn)
 pack = raw_input('Number of packages: ')
 pack = int(pack)
 print startFrom, '--->', arriveTo, ': ', pack
 if startFrom in capacity:#Style change and more pythonic
  capacity[startFrom] = capacity[startFrom] + pack
 else:
  capacity[startFrom] = pack
print capacity

那应该解决它。