对我的代码进行故障排除 - 通过从raw_input()获取的密钥名称引用时出现密钥错误

时间:2013-12-23 13:37:21

标签: python dictionary raw-input

这部分等式是我不需要帮助的部分。这基本上要求用户输入游戏中玩家的数量,并为一个主词典中的每个玩家创建一个子词典:

ans = raw_input('Enter Amount of Players: ').lower()
if ans == '2':
    a = raw_input('What is Player 1 named: ')
    b = raw_input('What is Player 2 named: ')
    cf={a:{}, b:{}}
    p1 = raw_input(a + ", what is your city named: ")  
    p2 = raw_input(b + ", what is your city named: ") 
    cf[a][p1] = '50'
    cf[b][p2] = '50'
    for key, cf in cf.items():
        print(key)
        for attribute, value in cf.items():
            print('{} : {}'.format(attribute, value)) 

以下是我需要帮助的部分:

##This function may be screwing it up
def cva(x):
    y = cf[ques][city]
    y = float(y)
    return x + y

while True:
    one = raw_input("Type 'view' to view civil form, type 'change' to change civil order,   or 'add' to add a city: ")
 if one == 'change':
        ques = raw_input('Enter Name of Player That Will Change His/Her Civil Form: ').lower()
        city = raw_input(ques + 'Enter Name Of City That Will Change Civil Form: ').lower()
        inc = raw_input(ques + ' Enter Amount of change for ' + city + ": ").lower()
        cf[ques][city]=cva(float(inc))
        for key, cf in cf.items():
            print(key)
            for attribute, value in cf.items():
                print('{} : {}'.format(attribute, value))

假设我输入了'evan'这个名字和他的城市'LA',会出现一个错误:'KeyError:'evan'。我如何让它工作?

3 个答案:

答案 0 :(得分:1)

您需要确保之前已将播放器添加到词典中。您还应该规范化输入和字典键。

假设您不需要为人们支持区分大小写的唯一名称,请添加:

if ques.lower() not in [key.lower() for key in cf.keys()]:
    print "Player record does not exist - please create player before updating."
    continue
输入播放器名称之后

将是处理此类事情的一种方式。

答案 1 :(得分:0)

问题是您必须在致电dic功能之前更新cva。否则,y = cf[ques][city]函数中的cva将没有更新的城市值。

前:

while True:
    one = raw_input("Type 'view' to view civil form, type 'change' to change civil order,   or 'add' to add a city: ")
    if one == 'change':
        ques = raw_input('Enter Name of Player That Will Change His/Her Civil Form: ').lower()
        city = raw_input(ques + 'Enter Name Of City That Will Change Civil Form: ').lower()
        inc = raw_input(ques + ' Enter Amount of change for ' + city + ": ").lower()
        cf[ques].update({city:0}) # create the entry in the dic
        cf[ques][city] = cva(float(inc))
        # ...

正如@selllikesybok所说,在迭代之前添加一些验证dic的代码。

答案 2 :(得分:0)

实际上问题是由于您认为第一段代码中存在错误 请注意,在您拥有的for循环中:

    for key, cf in cf.items():
        print(key)
        for attribute, value in cf.items():
            print('{} : {}'.format(attribute, value))

然而,问题在于for key, cf in cf.items():会在执行时更改cf的值。

如果您将第二个目标变量的名称从cf更改为与任何现有变量不冲突的其他内容,则您的第二部分将无法获得KeyError 'evan'更长。
例如:

    for key, info in cf.items():
        print(key)
        for attribute, value in info.items():
            print('{} : {}'.format(attribute, value))