Reputation: 163
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?
Upvotes: 1
Views: 88
Reputation: 863711
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']
Upvotes: 1