【问题标题】:print key and only one value from dictionary打印键和字典中只有一个值
【发布时间】:2018-01-20 20:36:58
【问题描述】:

下面是字典:

std[name]={'uid':uid ,'age':age,'subject':{'math':math,'phy':phy,'chem':chem}}

输出应该是:

列出 nameuid

这是我的代码:

std={}
i=0
n=int(raw_input("How many Entries you have to fill:"))
for i in range (n):
   name=raw_input("Enter name:")
   uid=raw_input("ID:")
   age=raw_input("Age:")
   print("----Marks----")
   math=raw_input("Maths:")
   phy=raw_input("Physics:")
   chem=raw_input("Chemistry:")
   std[name]={'Uid':uid,'Age':age,'subject'{'math':math,'phy':phy,'chem':chem}}
   print('\n')
print(std['name']['uid'])

【问题讨论】:

  • print(std['name']['uid'])?
  • 出现错误:print(std['name']['uid']) KeyError: 'name'
  • 那是因为name 之前没有在你的代码中定义
  • 您的示例中的名称没有被引用 - 它是一个变量吗?如果是这样,您需要在 dict 查找中使用不带引号的(或引用的字符串)。
  • 看看你的帖子。代码很乱。

标签: python dictionary


【解决方案1】:

python 3.x你可以使用:

for k,v in std.items():
    print(k,v['Uid'])

python 2.x:

for k,v in std.iteritems():
        print(k,v['Uid'])

python 3.x代码:

std={}
n=int(input("How many Entries you have to fill:"))

for i in range (n):
    name=input("Enter name:")
    uid=input("ID:")
    age=input("Age:")
    print("----Marks----")
    math=input("Maths:")
    phy=input("Physics:")
    chem=input("Chemistry:")
    std[name]={'Uid':uid,'Age':age,'subject':{'math':math,'phy':phy,'chem':chem}}
    print('\n')
for k,v in std.items():
    print(k,v['Uid'])

2 个不同名称的输入和结果将是:

How many Entries you have to fill:2

Enter name:John
ID:15895
Age:18
----Marks----
Maths:15
Physics:15
Chemistry:15


Enter name:Beck
ID:52256
Age:54
----Marks----
Maths:52
Physics:52
Chemistry:21


John 15895
Beck 52256

【讨论】:

    猜你喜欢
    • 2020-06-18
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多