如何从字典中获取值列表?
- 2024-12-18 08:38:00
- admin 原创
- 133
问题描述:
如何在 Python 中获取字典中的值列表?
在 Java 中,获取 Map 的值作为 List 非常简单list = map.values();
。我想知道在 Python 中是否有类似的简单方法可以从字典中获取值列表。
解决方案 1:
dict.values
返回字典值的视图,因此必须将其包装在list
:
list(d.values())
解决方案 2:
您可以使用* 运算符来解包 dict_values:
>>> d = {1: "a", 2: "b"}
>>> [*d.values()]
['a', 'b']
或列表对象
>>> d = {1: "a", 2: "b"}
>>> list(d.values())
['a', 'b']
解决方案 3:
应该有一种(最好只有一种)明显的方法来做到这一点。
因此list(dictionary.values())
这是唯一的方法。
然而,考虑到 Python3,哪个更快?
[*L]
对阵[].extend(L)
对阵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
结果
对于小型词典来说
* operator
更快对于重要的大型词典来说,
list()
可能稍微快一点
解决方案 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}
')
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))))
解决方案 5:
如果需要将值作为列表分配给变量,则使用解包运算*
符的另一种方法是
*values, = 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()
从内置operator
模块中获取 keys: 下的值。
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']
解决方案 6:
如果您希望list
默认返回 a (如在 Python 2 中)而不是 a view
,则可以创建一个新的 dict 类并覆盖该values
方法:
class ldict(dict):
# return a simple list instead of dict_values object
values = lambda _: [*super().values()]
d = ldict({'a': 1, 'b': 2})
d.values() # [1, 2] (instead of dict_values([1, 2]))
解决方案 7:
out: dict_values([{1:a, 2:b}])
in: str(dict.values())[14:-3]
out: 1:a, 2:b
纯粹用于视觉目的。不会产生有用的产品...仅当您想以段落形式打印长词典时才有用。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD