Home > front end >  Decouple dictionary that contains a list as a value for a particular key
Decouple dictionary that contains a list as a value for a particular key

Time:05-14

Let's say I have a dict in Python that follows this structure:

dict_a = {"a": [1,2,3]}

I want to produce an output to 'decouple' dict_a in a list of 3 separate dicts like

>>> [{"a": 1}, {"a": 2}, {"a": 3}]

What I have now is:

dict_a = {"a": [1,2,3]}
result = []

for key, values in dict_a.items():
    for value in values:
        result.append({key: value})

print(result)
>>> [{"a": 1}, {"a": 2}, {"a": 3}]

Is there any way to achieve this or a similar 'decoupling' behavior with list comprehension or a dict related method?

CodePudding user response:

While the for loops are quite pythonic and readable, the same can be achieved with comprehensions:

dict_a = {"a": [1,2,3]}
result = [{k: v} for k, vs in dict_a.items() for v in vs]
  • Related