我有一个字典列表,像这样:

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

我想要['苹果','香蕉','汽车']

做这件事最好的方法是什么?


当前回答

遵循这个例子——

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))))

其他回答

从python字典列表中获取键值?

从python字典列表中获取键值?

Ex:

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

对于数据中的d:

  for key,value in d.items(): 

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

输出:

{'obj1': {'cpu_percentage': '15%', 'memory_percentage': '66%'}}
{'obj2': {'cpu_percentage': '0', 'memory_percentage': '35%'}}

假设每个字典都有一个值键,你可以这样写(假设你的列表名为l)

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

如果价值可能丢失,您可以使用

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

使用列表推导式

输入:

d = [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3}, {'value': 'cars', 'blah': 4}]
    
        
values = [i['value'] for i in d]

print(values)

输出:

['apple', 'banana', 'cars']
[x['value'] for x in list_of_dicts]

下面是使用map()和lambda函数的另一种方法:

>>> map(lambda d: d['value'], l)

其中l是列表。 我这样看“最性感”,但我会用列表理解来做。

更新: 以防“value”作为键的使用可能会丢失:

>>> map(lambda d: d.get('value', 'default value'), l)

更新:我也不是lambdas的大粉丝,我更喜欢命名事物…这就是我的做法:

>>> import operator
>>> get_value = operator.itemgetter('value')
>>> map(get_value, l)

我甚至会进一步创建一个明确表示我想要实现的功能:

>>> import operator, functools
>>> get_value = operator.itemgetter('value')
>>> get_values = functools.partial(map, get_value)
>>> get_values(l)
... [<list of values>]

在Python 3中,由于map返回一个迭代器,所以使用list返回一个列表,例如list(map(operator.itemgetter('value'), l))。