简体   繁体   English

如何从 dict 获取值列表?

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

How can I get a list of the values in a dict in Python?如何在 Python 中获取 dict 中的值列表?

In Java, getting the values of a Map as a List is as easy as doing list = map.values();在 Java 中,将 Map 的值作为 List 获取就像list = map.values();一样简单。 . . I'm wondering if there is a similarly simple way in Python to get a list of values from a dict.我想知道 Python 中是否有类似的简单方法可以从字典中获取值列表。

dict.values返回字典值的 视图,因此您必须将其包装在list

list(d.values())

You can use * operator to unpack dict_values:你可以使用* 操作符来解压 dict_values:

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

or list object或列表对象

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

There should be one ‒ and preferably only one ‒ obvious way to do it.应该有一种——最好只有一种——明显的方法来做到这一点。

Therefore list(dictionary.values()) is the one way .因此list(dictionary.values())一种方式

Yet, considering Python3, what is quicker?然而,考虑到 Python3,什么更快?

[*L] vs. [].extend(L) vs. list(L) [*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)

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

# Name                    Version                   Build
ipython                   7.5.0            py37h24bf2e0_0

The result结果

  1. For small dictionaries * operator is quicker对于小型字典* operator更快
  2. For big dictionaries where it matters list() is maybe slightly quicker对于重要的大字典list()可能会稍微快一些

Follow the below example --按照下面的例子——

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))))
  • Get a list of values of specific keys in a dictionary获取字典中特定键的值列表

Most straightforward way is to use a comprehension by iterating over list_of_keys .最直接的方法是通过迭代list_of_keys来使用理解。 If list_of_keys includes keys that are not keys of d , .get() method may be used to return a default value ( None by default but can be changed).如果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]

As often the case, there's a method built into Python that can get the values under keys: itemgetter() from the built-in operator module.通常情况下,Python 中内置了一种方法,可以获取键下的值:来自内置operator模块的itemgetter()

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

Demonstration:示范:

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]
  • Get values of the same key from a list of dictionaries从字典列表中获取相同键的值

Again, a comprehension works here (iterating over list of dictionaries).再一次,理解在这里起作用(迭代字典列表)。 As does mapping itemgetter() over the list to get the values of specific key(s).与在列表上映射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

Purely for visual purposes.纯粹出于视觉目的。 Does not produce a useful product... Only useful if you want a long dictionary to print in a paragraph type form.不会产生有用的产品...仅当您希望以段落类型的形式打印长字典时才有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM