简体   繁体   中英

How to convert nested dictionary to list with key orders

I want to make a list out of the nested dictionary:

 {'Name': {'20': 'Paul Merrill', '21': 'Brynne S. Barr', }, 
 'Phone': {'20': '1-313-739-3854', '21': '939-4818', }, 
 'Address': {'20': '916-8087 Vehicula Rd.', '21': '878-2231 Suspendisse Rd.', },
 'City': {'20': 'Le Mans', '21': 'Wilhelmshaven',}

to a list with '20' as the identifier, so it will be something like this:

['20', 'Paul Merril', '1-313-739-3854', '916-8087 Vehicula Rd.', 'Le Mans']

I have tried to use value and key options, but they don't seem to work. Could someone help me with this?

Use a list comprehension :

L = [v['20'] for k, v in d.items()] 
#alternative if some key 20 is missing
L = [v.get('20') for k, v in d.items()] 

Or solution from @Henry Yik, thank you:

L = [v.get("20") for v in d.values()]
print (L)
['Paul Merrill', '1-313-739-3854', '916-8087 Vehicula Rd.', 'Le Mans']

If also need prepend 20 :

L = ['20'] + L

Or:

L = ['20', *L]

print (L)
['20', 'Paul Merrill', '1-313-739-3854', '916-8087 Vehicula Rd.', 'Le Mans']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM