ratchet
ratchet

Reputation: 195

Convert a list of lists to a dictionary

How do I create a dictionary from a Python list of lists so that the first row are the keys and the rest are a list under that key?

x = [['A', 'B', 'C'],
 [100, 90, 80],
 [88, 99, 111],
 [45, 56, 67],
 [59, 61, 67],
 [73, 79, 83],
 [89, 97, 101]]

Currently with a dict comprehension I am getting:

{i[0]: i[1:] for i in x}

{'A': ['B', 'C'],
 100: [90, 80],
 88: [99, 111],
 45: [56, 67],
 59: [61, 67],
 73: [79, 83],
 89: [97, 101]}

The desired result is:

{
"A": [100, 88, 45, 59, 73, 89],
"B": [90, 99, 56, 61, 79, 97],
"C": [80, 111, 67, 83, 101],
}

How do I slice the dictionary comprehension the correct way?

Upvotes: 2

Views: 4584

Answers (2)

Mehrdad Dowlatabadi
Mehrdad Dowlatabadi

Reputation: 1335

For loop and list comprehension:

x = [['A', 'B', 'C'],
[100, 90, 80],
[88, 99, 111],
[45, 56, 67],
[59, 61, 67],
[73, 79, 83],
[89, 97, 101]]
dict1={}

for i,k in  enumerate( x[0]):
    dict1[k]=[x1[i] for x1 in x[1:]]
print(dict1)
#{'A': [100, 88, 45, 59, 73, 89], 'B': [90, 99, 56, 61, 79, 97], 'C': [80, 111, 67, 67, 83, 101]}

Upvotes: 0

iBug
iBug

Reputation: 37227

You have zip as an option:

wanted = {a[0]: list(a[1:]) for a in zip(*x)}

Or if you're familiar with unpacking:

wanted = {k: v for k, *v in zip(*x)}

Upvotes: 7

Related Questions