Reputation: 97
I'm trying to convert the nested list below
input_list = [['a', [1, 2, 3]], ['b', [2, 4, 5]], ['c', [3, 7, 8]]]
into a list of a dictionary as below.
output: [{"a":1, "b":2, "c":3}, {"a":2, "b":4, "c":7}, {"a":3, "b":5, "c":8}]
This is what I have tried but not sure how to expand the list to values and categorize them into one dictionary.
My Code:
dict( (k[0], k[1:]) for k in l1)
I get the output as:
{'a': [[1, 2, 3]], 'b': [[2, 4, 5]], 'c': [[3, 7, 8]]}
I'm guessing I need to use functions like zip or map. I'm not sure. Really appreciate any solution. Thank you.
Upvotes: 0
Views: 93
Reputation: 3100
If you don't want to use any list-/dict-comprehension and only use for-loops then you can do this:
input_list = [['a', [1, 2, 3]], ['b', [2, 4, 5]], ['c', [3, 7, 8]]]
newList = []
for key, values in input_list:
for idx, value in enumerate(values):
if len(newList) -1 < idx:
newList.append({key: value})
else:
newList[idx].update({key:value})
for i in newList:
print(i)
Output:
{'a': 1, 'b': 2, 'c': 3}
{'a': 2, 'b': 4, 'c': 7}
{'a': 3, 'b': 5, 'c': 8}
This code will work even if your lists aren't the same length.
if we set input_list
to this:
input_list = [['a', [9, 7, 3, 2]], ['b', [4, 7, 8, 8, 2, 5]], ['c', [1, 2, 2]], ['d', [4, 4, 2, 1]], ['e', [6, 2]]]
Then the output will be:
{'a': 9, 'b': 4, 'c': 1, 'd': 4, 'e': 6}
{'a': 7, 'b': 7, 'c': 2, 'd': 4, 'e': 2}
{'a': 3, 'b': 8, 'c': 2, 'd': 2}
{'a': 2, 'b': 8, 'd': 1}
{'b': 2}
{'b': 5}
Upvotes: 1
Reputation: 107124
You can zip
the sub-lists of values to align them with the keys so that you can zip the keys and values as input to the dict
constructor:
[dict(zip((k for k, _ in input_list), v)) for v in zip(*(v for _, v in input_list))]
Upvotes: 1
Reputation: 6600
You can just use zip
like,
>>> x
[['a', [1, 2, 3]], ['b', [2, 4, 5]], ['c', [3, 7, 8]]]
>>> keys, values = zip(*x) # extract the keys and values
>>> keys
('a', 'b', 'c')
>>> values
([1, 2, 3], [2, 4, 5], [3, 7, 8])
>>>
>>> [dict(zip(keys, value)) for value in values]
[{'a': 1, 'b': 2, 'c': 3}, {'a': 2, 'b': 4, 'c': 5}, {'a': 3, 'b': 7, 'c': 8}]
Upvotes: 1
Reputation: 150825
You can try this:
[dict(pairs) for pairs in zip(*[[(a, v) for v in l ]
for a, l in input_list])
]
Output:
[{'a': 1, 'b': 2, 'c': 3}, {'a': 2, 'b': 4, 'c': 7}, {'a': 3, 'b': 5, 'c': 8}]
Upvotes: 0