zogo
zogo

Reputation: 515

want to output the nested dictionary value

i am relatively new in python.I am working with the dictionary.In my dictionary there are two list values are inserted as below,

speed = ['20','30','25','50','40']
time = ['10','11','12','13','14']
dic = {'name':'Finder','details':'{ time : speed }'}

now i just want to get output just like that,

10:20
11:30
12:25
13:50
14:40

which associated with the time:speed for that i write a for loop which is just like that,

for k,i in dic.items()
     print(k + ":" + i)

after executing the code i get an error which is just like that,

unhashable type list

is the error for the nested dictionary?? my another question is ,the for loop i write ,is it the perfect to get the output of the nested dictionary value??

please help me to fix these problems.

Upvotes: 0

Views: 78

Answers (3)

perreal
perreal

Reputation: 98118

speed = ['20','30','25','50','40']
time = ['10','11','12','13','14']
dic = {'name':'Finder','details':'{ time : speed }'}

l1,l2 = [locals()[x.strip("{} ")] 
        for x in dic['details'].split(":")]

for p in zip(l1, l2):
    print ":".join(p)

Gives:

10:20
11:30
12:25
13:50
14:40

Upvotes: 1

falsetru
falsetru

Reputation: 369444

You cannot use list as the dictionary key.

>>> speed = ['20','30','25','50','40']
>>> time = ['10','11','12','13','14']
>>> {time: speed}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Convert the list to tuple to use it as key.

>>> {tuple(time): speed}
{('10', '11', '12', '13', '14'): ['20', '30', '25', '50', '40']}

And you don't need to use dictionary to get the desired output.

Using zip:

>>> speed = ['20','30','25','50','40']
>>> time = ['10','11','12','13','14']
>>> for t, s in zip(time, speed):
...     print('{}:{}'.format(t, s))
...
10:20
11:30
12:25
13:50
14:40

Upvotes: 2

Nafiul Islam
Nafiul Islam

Reputation: 82600

Well, you can use a dictionary comprehension, and use zip to combine the two. The problem you are having is this, you are using a list as a dictionary key, and that is not possible, because a list is unhashable. SO for your example:

speed = ['20', '30', '25', '50', '40']
time = ['10', '11', '12', '13', '14']

for key, value in zip(time, speed):
    print key, ":", value


print

# Or you could have a dictionary comprehension, to make it
d = {key: value for key, value in zip(time, speed)}

for key, value in d.items():
    print key, ":", value

Output

10 : 20
11 : 30
12 : 25
13 : 50
14 : 40

11 : 30
10 : 20
13 : 50
12 : 25
14 : 40

Upvotes: 1

Related Questions