Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am trying to convert list to dictionary

my_dict = {}

book_ratings = [['Ben'],['5', '0', '1', '4'], ['Sally'],['0', '7', '3', '3']]

I am trying to return the names ["Ben"], ["Sally"] as my keys and ratings ["5","0","1","4"], ["0","7","3","3"] as values.

Trying to get the output like this:

 {"Ben": ["5", "0", "1", "4"], "Sally": ["0", "7", "3", "3"]}

1 Answer

0 votes
by (36.8k points)
edited by

If my structure of book_ratings is the Name, List, Name, List, ... you can use the example below to construct the dictionary:

book_ratings = [["Ben"],["5", "0", "1", "4"], ["Sally"],["0", "7", "3", "3"]]

i = iter(book_ratings)

my_dict = dict((a[0], b) for a, b in zip(i, i))

print(my_dict)

Prints:

{'Ben': ['5', '0', '1', '4'], 'Sally': ['0', '7', '3', '3']}

Or:

my_dict = dict((a, b) for (a,), b in zip(book_ratings[::2], book_ratings[1::2]))

 Do check out data science with python certification to understand from scratch

Browse Categories

...