我有一个字典列表,像这样:
[{'value': 'apple', 'blah': 2},
{'value': 'banana', 'blah': 3} ,
{'value': 'cars', 'blah': 4}]
我想要['苹果','香蕉','汽车']
做这件事最好的方法是什么?
我有一个字典列表,像这样:
[{'value': 'apple', 'blah': 2},
{'value': 'banana', 'blah': 3} ,
{'value': 'cars', 'blah': 4}]
我想要['苹果','香蕉','汽车']
做这件事最好的方法是什么?
当前回答
请试试这个。
d =[{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3} , {'value':
'cars', 'blah': 4}]
b=d[0]['value']
c=d[1]['value']
d=d[2]['value']
new_list=[b,c,d]
print(new_list)
输出:
['apple', 'banana', 'cars']
其他回答
遵循这个例子——
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))))
下面是使用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))。
[x['value'] for x in list_of_dicts]
一个非常简单的方法是:
list1=['']
j=0
for i in com_list:
if j==0:
list1[0]=(i['value'])
else:
list1.append(i['value'])
j+=1
输出:
['apple', 'banana', 'cars']
使用列表推导式
输入:
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']