从Python字典加载数字

从Python字典加载数字,python,directory,Python,Directory,我试图通过使用一本有两个不同细节的词典来解决这个问题: direc = {} a = 17 b = 165 direc.update({a: b}) a = 19 b = 174 direc.update({a: b}) for x,y in direc: print('age:' +str(x) + ' and height :'+str(y)) 我需要输出为: age:17 and height:165 age:19 and height:174 {}用于使字典不是目录。无

我试图通过使用一本有两个不同细节的词典来解决这个问题:

direc = {}

a = 17
b = 165
direc.update({a: b})

a = 19
b = 174
direc.update({a: b})

for x,y in direc:
    print('age:' +str(x) + ' and height :'+str(y))
我需要输出为:

age:17 and height:165
age:19 and height:174
{}用于使字典不是目录。无论如何,要回答您的问题,您可以将
a
b
保存为direc中的一个键。您可以通过以下方式实现这一目标:

direc={}

a=17
b=165
direc[a]= b

a=19
b=174
direc[a]= b

for x,y in direc.items(): # note: you need to use .items() it iterate through them
    print('age:' +str(x) + ' and height :'+str(y))
但这并不是挽救年龄和身高的最好办法。因为如果有两个年龄相同,它将覆盖第一个年龄。你应该像这样做:

direc["name"]=(a, b) # the name of the person
这样,如果您键入此人的姓名,它将返回其年龄和身高

direc={}

direc["personA"]= (17,165)  # you don't need to define a or b

direc["personB"]= (19,174)
for x,y in direc.items():
    print('name:' + str(x) + ', age:' +str(y[0]) + ' and height :'+str(y[1]))

更简单地说,只需将初始目录值作为文字:

direc = {17: 165, 19: 174}
for age, ht in direc.items():
    print('age:', age, ' and height:', ht)
您不必一次构建一个条目的字典。另外,请注意,print允许您提供值列表——您不必转换数字并将它们连接到输出行。

使用
direc.items()
而不是
direc
(它只提供键,而不是键+值对)


目录?你是说字典吗?因为你在用字典。字典不能有重复的键。这是您的问题。谢谢,但是现在我如何将字典拆分为两个不同的变量并打印输出,您的两个解决方案都不起作用。您没有测试它们吗?@abccd崩溃时出现
TypeError:“int”对象不可编辑
ValueError:值太多,无法解压缩(预期为2个)
for x,y in direc.items():
    print('age:' +str(x) + ' and height :'+str(y))