如何在Python中获得dict中的值列表?

在Java中,获取Map作为List的值就像执行List = Map .values();一样简单。我想知道在Python中是否有类似的简单方法来从字典中获取值列表。


当前回答

字典Values返回一个字典值的视图,所以你必须将它包装在list中:

list(d.values())

其他回答

字典Values返回一个字典值的视图,所以你必须将它包装在list中:

list(d.values())

获取字典中特定键的值列表

最直接的方法是通过迭代list_of_keys来使用理解式。如果list_of_keys包含不是d的键,.get()方法可用于返回默认值(默认为None,但可以更改)。

res = [d[k] for k in list_of_keys] 
# or
res = [d.get(k) for k in list_of_keys]

通常情况下,Python中内置了一个方法,可以从内置操作符模块获取键下的值:itemgetter()。

from operator import itemgetter
res = list(itemgetter(*list_of_keys)(d))

演示:

d = {'a':2, 'b':4, 'c':7}
list_of_keys = ['a','c']
print([d.get(k) for k in list_of_keys])
print(list(itemgetter(*list_of_keys)(d)))
# [2, 7]
# [2, 7]

从字典列表中获取相同键的值

同样,这里使用了理解(遍历字典列表)。在列表上映射itemgetter()以获取特定键的值也是如此。

list_of_dicts = [ {"title": "A", "body": "AA"}, {"title": "B", "body": "BB"} ]

list_comp = [d['title'] for d in list_of_dicts]
itmgetter = list(map(itemgetter('title'), list_of_dicts))
print(list_comp)
print(itmgetter)
# ['A', 'B']
# ['A', 'B']

你可以使用*操作符解包dict_values:

>>> d = {1: "a", 2: "b"}
>>> [*d.values()]
['a', 'b']

或列表对象

>>> d = {1: "a", 2: "b"}
>>> list(d.values())
['a', 'b']
out: dict_values([{1:a, 2:b}])

in:  str(dict.values())[14:-3]    
out: 1:a, 2:b

纯粹是为了视觉效果。没有生产出有用的产品…只有当你想要以段落形式打印一本长字典时才有用。

遵循下面的例子——

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