Good day.

There is a dictionary like: {"id1": "Aaa", "id2": "Bbb"} .

How to parse it into the nth number of dictionaries by the principle: {"name": "id1", "value": "Aaa"}, {"name": "id2", "value": "Bbb"}

Thank.

    2 answers 2

     In [56]: [{'name':key, 'value':val} for key,val in d.items()] Out[56]: [{'name': 'id1', 'value': 'Aaa'}, {'name': 'id2', 'value': 'Bbb'}] 

    or

     In [55]: [dict(name=key, value=val) for key,val in d.items()] Out[55]: [{'name': 'id1', 'value': 'Aaa'}, {'name': 'id2', 'value': 'Bbb'}] 
    • Will there be a difference in speed between your and my answer with a large dictionary at the entrance? - Igor Lavrynenko
    • @IgorLavrynenko, I think they will not be very different in speed ... - MaxU
    • I use the answer method all the time, but then I thought maybe I can win something using your option - Igor Lavrynenko

    Or so:

     >>> a = {"id1": "Aaa", "id2": "Bbb"} >>> print([{'name': i, 'value': a[i]} for i in a]) [{'value': 'Aaa', 'name': 'id1'}, {'value': 'Bbb', 'name': 'id2'}]