字典值在打印时不会显示在代码的后续部分中

时间:2013-12-23 15:35:10

标签: python dictionary

忽略所有这些鳕鱼,除了我指出的斑点,我会说##看这里##的地方:

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:{}}
    cf[a] = a
    cf[b] = b
    p1 = raw_input(a + ", what is your city named: ")  
    p2 = raw_input(b + ", what is your city named: ")
    cf={a:{p1:50}, b:{p2:50}}
    ##Look here, print cf ##
    print cf
    for key, cf in cf.items():
        print(key)
        for attribute, value in cf.items():
            print('{} : {}'.format(attribute, value))

answer = raw_input ("Hit 'Enter' to continue")

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()
        ##Look here, print cf##
        print cf
        cf[ques][city]=cva(float(inc))
        for key, cf in cf.items():
            print(key)
            for attribute, value in cf.items():
                print('{} : {}'.format(attribute, value))
    elif one == 'view':
        for key, cf in cf.items():
            print(key)
            for attribute, value in cf.items():
                print('{} : {}'.format(attribute, value))
    elif one == 'add':
        ch1 = raw_input('Enter the Name of Player That Will Add a City: ')
        ch2 = raw_input(ch1 + ', Enter The Name of Your New City: ')
        cf[ch1][ch2] = '50'
    elif one == 'over': break
    elif one == 'game over': break
    elif one == 'quit': break

我告诉你看的代码的两部分基本上是打印字典。当我输入名称'Andrew'和'Matt',以及城市'Po'和'Lo'时,第一个印刷品看起来像这样:{'Matt': {'Lo': 50}, 'Andrew': {'Po': 50}} 第二个印刷品对于Matt来说是这样的:{'Po': 50} 安德鲁的第二个印刷品看起来像这样:{'Lo': 50} 为什么播放器的名称不会像第一次打印中那样显示在第二个打印件中。是因为这个名字被删除了吗?如果是这样,你能告诉我如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

问题是你的循环

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

由于您将其中一个迭代变量命名为与您迭代的字典相同的东西,因此您遇到了问题。 在此循环之后,cf将包含最后一项

将迭代变量cf重命名为其他内容,例如

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

事情应该没问题。