Reputation:
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))})
I want to print 15 items in a dictionary format of name as key and dateofbirth(dob) as value.What wrong I am doing? .....................................................................................
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'
Upvotes: 1
Views: 49
Reputation: 178
The issue is not in the print() function but in the way you make up the first list: instead of pulling out the names, it gives you a (<class 'str'>, 'string')
tuple that cannot be used as a key for a dictionary. The same happens with the 'dob' variable, but the issue is only with keys.
Try doing:
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
Upvotes: 1
Reputation: 140
I would do it like this (this returns a generator):
name = map(str, input().split())
dob = map(int, input().split())
print({n: d for n, d in zip(name, dob)})
If you want it to return a list instead:
name = list(map(str, input().split()))
dob = list(map(int, input().split()))
print({n: d for n, d in zip(name, dob)})
Upvotes: 0