Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Decouple dictionary that contains a list as a value for a particular key

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 ‘decoupledict_a in a list of 3 separate dicts like

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

What I have now is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading