首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在打印字典值时,它们不会显示在后面的代码段中

在打印字典值时,它们不会显示在后面的代码段中
EN

Stack Overflow用户
提问于 2013-12-23 23:35:10
回答 1查看 56关注 0票数 0

忽略所有这些代码,除了我指出的那些点,我将在这些点上说##Look Here##:

代码语言:javascript
复制
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}}第二张照片是这样的:{'Po': 50}第二张照片像Andrew:{'Lo': 50}为什么球员的名字没有像第一张照片一样出现在第二张照片里。是因为名字被删除了吗?如果是这样,你能告诉我如何解决这个问题吗?

EN

回答 1

Stack Overflow用户

发布于 2013-12-23 23:47:10

问题出在你的循环上

代码语言:javascript
复制
for key, cf in cf.items():
        for attribute, value in cf.items():
            print('{} : {}'.format(attribute, value))

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

将迭代变量cf重命名为其他名称,如

代码语言:javascript
复制
for key, dict_val in cf.items():
            for attribute, value in dict_val.items():
                print('{} : {}'.format(attribute, value))

一切都会好起来的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20746594

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档