How to convert nested dictionary to list with key orders

前端 未结 1 655
旧巷少年郎
旧巷少年郎 2021-01-25 08:09

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

 {\'Name\': {\'20\': \'Paul Merrill\', \'21\': \'Brynne S. Barr\', }, 
 \'Phone\': {\'20\': \'1-313-739-38         


        
相关标签:
1条回答
  • 2021-01-25 08:39

    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']
    
    0 讨论(0)
提交回复
热议问题