Home > OS >  How to convert list of dictionary to dict using the list of dict values
How to convert list of dictionary to dict using the list of dict values

Time:10-24

I dont know how to start with this and would love to any help.

i have this list of dict:

mylist_of_dict = 
[{"plat": "Linux",
  "os_name": "Android",
}, {
  "plat": "Linux",
  "os_name": "Chrome OS",
}, {
  "plat": "Win32",
  "os_name": "Windows",
}]

My main goal is to transform it into this dict where the plat key value is now the key and the os_name are values:

{'Linux':["Android", "Chrome OS"],
'Win32': ["Windows",]}

Any help will be highly appreciated.

CodePudding user response:

Try:

out = {}
for d in mylist_of_dict:
    out.setdefault(d["plat"], []).append(d["os_name"])

print(out)

Prints:

{"Linux": ["Android", "Chrome OS"], "Win32": ["Windows"]}
  • Related