2016-12-08 77 views
1

我的字典代码出现问题。我至今是这个 -在字典中添加值

def get_info(): 
    answer = "yes" 
    d = {} 
    while answer == "yes": 
     a = input("Enter name: ") 

     b = int(input("Enter hours: ")) 
     if b > 10 or b < 1: 
      b = int(input("Enter hours: ")) 

     d[a] = b 
     answer = yes_no("More Shifts?: ") 

    if answer == "yes": 
     get_info() 
    elif answer == "no":  
     print(d) 

def yes_no(msg): 
    a = input(msg) 
    while a!= "yes" and a!= "no": 
     a = input("Enter yes or no: ") 
    return a 

def main(): 
    get_info() 

它是通过将所有输入正确我的字典工作完美,但我似乎无法找到一种方法,让这个如果我输入,例如, “安迪”,然后是“2”,然后是“安迪”和“2”,以使我的字典在最后打印出“安迪”:4.另一个参考例子是“丹”5和“丹”3.我的代码将只打印丹3而不是两者的总和。我希望我能清楚地描述这个问题,让任何人都能理解。谢谢您的帮助!

+1

@MooingRawr在技术上不正确:他覆盖已存储的任何特定键的值。他只在'get_info()'开始时创建一次字典。 – TemporalWolf

回答

2

要做到这一点,你需要检查该名称是否已经在你的字典里,如果是使用+=而不是覆盖第一个值。

if a in d: 
    d[a] += b 
else: 
    d[a] = b 
+0

Python样式更喜欢[比许可更容易请求原谅](https://docs.python.org/2/glossary.html#term-eafp),而不是看你跳跃之前的方法。 – TemporalWolf

2

要追加新的信息,如果它不存在:

d[a] = b

应该

try: 
    d[a] += b 
except KeyError: 
    d[a] = b 

这是继蟒蛇造型的偏好,这是EAFP

1

每次用您的方法覆盖以前的值。

你需要的是defaultdict而不是标准字典,默认int类型。小例子:

import collections 

d = collections.defaultdict(int) 

d["Dan"] += 2 
d["Dan"] += 2 
d["Andy"] = 10 

print(d) 

结果:

defaultdict(<class 'int'>, {'Dan': 4, 'Andy': 10}) 
在上下文

d = collections.defaultdict(int) 
while answer == "yes": 
    ... 
    d[a] += b