Reputation: 488
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'}]
col3
only need to add first 2 columnUpvotes: 1
Views: 79
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
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