sim
sim

Reputation: 488

How to convert list of list to dictionary

event = [['col1','col2','col3'], ['A','B','C'], ['G','H','I'], ['J','K','L']]

Expected out [{'col1': 'A', 'col2':'B'},{'col1': 'G', 'col2':'H'},{'col1': 'J', 'col2':'K'}]

Code is below

list_ = []
for entry in event [1:]:
    row = {key: entry[idx] for idx, key in enumerate(event[0])}
    list_.append(row)
list_

My output is

[{'col1': 'A', 'col2': 'B', 'col3': 'C'},
 {'col1': 'G', 'col2': 'H', 'col3': 'I'},
 {'col1': 'J', 'col2': 'K', 'col3': 'L'}]

Upvotes: 1

Views: 79

Answers (2)

Guy
Guy

Reputation: 50809

You can slice event[0] with [:-1] to ignore the last value

event = [['col1', 'col2', 'col3'], ['A', 'B', 'C'], ['G', 'H', 'I'], ['J', 'K', 'L']]
list_ = []
for entry in event[1:]:
    row = {key: entry[idx] for idx, key in enumerate(event[0][:-1])}
    list_.append(row)

print(list_) # [{'col1': 'A', 'col2': 'B'}, {'col1': 'G', 'col2': 'H'}, {'col1': 'J', 'col2': 'K'}]

If you want to edit the names you can add a condition to check the values. With list comprehensions

list_ = [{'country' if key == 'col1' else 'type': entry[idx] for idx, key in enumerate(event[0][:-1])} for entry in event[1:]]

Upvotes: 4

not_speshal
not_speshal

Reputation: 23146

Use zip in a list comprehension:

>>> list(dict(zip(event[0][:-1],values[:-1])) for values in event[1:])
[{'col1': 'A', 'col2': 'B'},
 {'col1': 'G', 'col2': 'H'},
 {'col1': 'J', 'col2': 'K'}]

Upvotes: 1

Related Questions