vitaminSí
vitaminSí

Reputation: 49

How to convert a nested list into a dictionary?

I would like to take a nested list such as:

list = [[Name, Height, Weight],[Dan, 175, 75],[Mark, 165, 64], [Sam, 183, 83]]

and convert it into a dictionary like:

dict = {Name: [Dan,Mark, Sam], Height: [175, 165, 183], Weight: [75, 64, 83]}

my current code is unfortunately not really giving me the dictionary format I'm looking for.

i = 1
z = 0
for items in list[0]:
    dict[items] = [list[i][z]]
    i += 1
z += 1

can someone please assist me and find where I'm going wrong?

Upvotes: 1

Views: 1970

Answers (3)

Bill
Bill

Reputation: 11643

@Mustafa's answer is the most concise but if you are a beginner you might find it easier to break it down into steps.

data =[
    ['Name', 'Height', 'Weight'], 
    ['Dan', 175, 75], ['Mark', 165, 64], ['Sam', 183, 83]
]
keys = data[0]
values = [list(items) for items in zip(*data[1:])]
results = dict(zip(keys, values))

Upvotes: 2

SCKU
SCKU

Reputation: 833

Welcome to stackoverflow :)

We seldom use i++ i+=1 for loop count or step in python if we can easily use for i in ... even if we don't know how many list in it.

your original data is a list of list. first list is the key of dictionary, other list is each records.

we often use zip(*your_list) when your data (list in list) is equal length. zip function will help you rearrange your_list. the * in front of your_list means put each record in your_list to zip function's argument one by one
then put it in a for loop, like for rec in zip(list):.

so, you can write your code like:

your_dict = {}
for rec in zip(yout_list):
    k = rec[0] #dict key
    v = list(rec[1:]) #dict value, convert to list if needed
    your_dict[k] = v # set key and value

e.g.

enter image description here

that's it!

Upvotes: 2

Mustafa Aydın
Mustafa Aydın

Reputation: 18315

Separate the keys and the rest first, then construct the dictionary with zip:

keys, *rest = list_of_lists

out = dict(zip(keys, zip(*rest)))

where list_of_lists is what you called list (but please refrain from that as it shadows the builtin list). First * is slurping all the lists starting from second one. The second * in zip kind of transposes the lists to reorder them

to get

>>> out

{"Name": ("Dan", "Mark", "Sam"),
 "Height": (175, 165, 183),
 "Weight": (75, 64, 83)}

this gives tuples in the values but to get lists, you can map:

out = dict(zip(keys, map(list, zip(*rest))))

Upvotes: 5

Related Questions