我想用python打印字典

时间:2020-02-17 13:19:58

标签: python-3.x dictionary

l = {}
name = [(str, input().split()) for i in range(0, 15)]
dob = [(int, input().split()) for i in range(0, 15)]
print({name[i]:dob[i] for i in range(len(dob))})

我想以字典格式打印15个项目,以名称的形式作为键,以dateofbirth(dob)作为值。我在做什么错? ................................................... ...................................

the error is:
Traceback (most recent call last):                                                                                                
  File "main.py", line 4, in <module>                                                                                             
    print({name[i]:dob[i] for i in range(len(dob))})                                                                              
  File "main.py", line 4, in <dictcomp>                                                                                           
    print({name[i]:dob[i] for i in range(len(dob))})                                                                              
TypeError: unhashable type: 'list'   

2 个答案:

答案 0 :(得分:1)

问题不在print()函数中,而是在您组成第一个列表的方式中:与其提取名称,不如提供一个(<class 'str'>, 'string')元组,该元组不能用作字典。 'dob'变量也会发生同样的情况,但是问题只在于键。

尝试做:

name = [input() for i in range(0, 15)] #this takes and returns the input. no need to convert to string
dob = [int(input()) for i in range(0, 15)] #this takes an input and returns it's numeric value

答案 1 :(得分:0)

我会这样(返回一个生成器):

name = map(str, input().split())
dob = map(int, input().split())
print({n: d for n, d in zip(name, dob)})

如果您希望它返回列表,则:

name = list(map(str, input().split()))
dob = list(map(int, input().split()))
print({n: d for n, d in zip(name, dob)})