簡體   English   中英

如何從 dict 獲取值列表?

[英]How can I get list of values from dict?

如何在 Python 中獲取 dict 中的值列表?

在 Java 中,將 Map 的值作為 List 獲取就像list = map.values();一樣簡單。 . 我想知道 Python 中是否有類似的簡單方法可以從字典中獲取值列表。

dict.values返回字典值的 視圖,因此您必須將其包裝在list

list(d.values())

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

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

或列表對象

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

應該有一種——最好只有一種——明顯的方法來做到這一點。

因此list(dictionary.values())一種方式

然而,考慮到 Python3,什么更快?

[*L] vs. [].extend(L) vs. list(L)

small_ds = {x: str(x+42) for x in range(10)}
small_df = {x: float(x+42) for x in range(10)}

print('Small Dict(str)')
%timeit [*small_ds.values()]
%timeit [].extend(small_ds.values())
%timeit list(small_ds.values())

print('Small Dict(float)')
%timeit [*small_df.values()]
%timeit [].extend(small_df.values())
%timeit list(small_df.values())

big_ds = {x: str(x+42) for x in range(1000000)}
big_df = {x: float(x+42) for x in range(1000000)}

print('Big Dict(str)')
%timeit [*big_ds.values()]
%timeit [].extend(big_ds.values())
%timeit list(big_ds.values())

print('Big Dict(float)')
%timeit [*big_df.values()]
%timeit [].extend(big_df.values())
%timeit list(big_df.values())
Small Dict(str)
256 ns ± 3.37 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
338 ns ± 0.807 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
336 ns ± 1.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Small Dict(float)
268 ns ± 0.297 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
343 ns ± 15.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
336 ns ± 0.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Big Dict(str)
17.5 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
16.5 ms ± 338 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
16.2 ms ± 19.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Big Dict(float)
13.2 ms ± 41 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
13.1 ms ± 919 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
12.8 ms ± 578 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

在 Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz 上完成。

# Name                    Version                   Build
ipython                   7.5.0            py37h24bf2e0_0

結果

  1. 對於小型字典* operator更快
  2. 對於重要的大字典list()可能會稍微快一些

按照下面的例子——

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))))
  • 獲取字典中特定鍵的值列表

最直接的方法是通過迭代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 中內置了一種方法,可以獲取鍵下的值:來自內置operator模塊的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']
out: dict_values([{1:a, 2:b}])

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

純粹出於視覺目的。 不會產生有用的產品...僅當您希望以段落類型的形式打印長字典時才有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM