Getting a list of values from a list of dicts

前端 未结 9 625
执念已碎
执念已碎 2020-11-22 15:22

I have a list of dicts like this:

[{\'value\': \'apple\', \'blah\': 2}, 
 {\'value\': \'banana\', \'blah\': 3} , 
 {\'value\': \'cars\', \'blah\': 4}]


        
相关标签:
9条回答
  • 2020-11-22 15:42

    Follow the example --

    songs = [
    {"title": "happy birthday", "playcount": 4},
    {"title": "AC/DC", "playcount": 2},
    {"title": "Billie Jean", "playcount": 6},
    {"title": "Human Touch", "playcount": 3}
    ]
    
    print("===========================")
    print(f'Songs --> {songs} \n')
    title = list(map(lambda x : x['title'], songs))
    print(f'Print Title --> {title}')
    
    playcount = list(map(lambda x : x['playcount'], songs))
    print(f'Print Playcount --> {playcount}')
    print (f'Print Sorted playcount --> {sorted(playcount)}')
    
    # Aliter -
    print(sorted(list(map(lambda x: x['playcount'],songs))))
    
    0 讨论(0)
  • 2020-11-22 15:45

    Assuming every dict has a value key, you can write (assuming your list is named l)

    [d['value'] for d in l]
    

    If value might be missing, you can use

    [d['value'] for d in l if 'value' in d]
    
    0 讨论(0)
  • 2020-11-22 15:49

    Get key values from list of dictionaries in python?

    1. Get key values from list of dictionaries in python?

    Ex:

    data = 
    [{'obj1':[{'cpu_percentage':'15%','ram':3,'memory_percentage':'66%'}]},
    {'obj2': [{'cpu_percentage':'0','ram':4,'memory_percentage':'35%'}]}]
    

    for d in data:

      for key,value in d.items(): 
    
          z ={key: {'cpu_percentage': d['cpu_percentage'],'memory_percentage': d['memory_percentage']} for d in value} 
          print(z)
    

    Output:

    {'obj1': {'cpu_percentage': '15%', 'memory_percentage': '66%'}}
    {'obj2': {'cpu_percentage': '0', 'memory_percentage': '35%'}}
    
    0 讨论(0)
提交回复
热议问题