问题:如何从字典中获取值列表?
如何在Python中获取字典中的值列表?
在Java中,将Map的值作为List变得容易list = map.values();
。我想知道Python中是否有类似的简单方法可以从字典中获取值列表。
回答 0
回答 1
您可以使用*运算符解压缩dict_values:
>>> d = {1: "a", 2: "b"}
>>> [*d.values()]
['a', 'b']
或列出对象
>>> d = {1: "a", 2: "b"}
>>> list(d.values())
['a', 'b']
回答 2
应该有一种方法,最好只有一种方法。
因此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®Core™i7-8650U CPU @ 1.90GHz上完成。
# Name Version Build
ipython 7.5.0 py37h24bf2e0_0
结果
- 对于小词典
* operator
更快 - 对于重要的大字典来说,
list()
可能会更快
回答 3
请按照以下示例-
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))))
回答 4
out: dict_values([{1:a, 2:b}])
in: str(dict.values())[14:-3]
out: 1:a, 2:b
纯粹出于视觉目的。不会产生有用的产品…仅在您希望长字典以段落类型形式打印时才有用。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。