dictから値のリストを取得するにはどうすればよいですか?


337

Pythonでdictの値のリストを取得するにはどうすればよいですか?

Javaでは、マップの値をリストとして取得するのは簡単list = map.values();です。Pythonで、dictから値のリストを取得する同様に簡単な方法があるかどうか疑問に思っています。

回答:


493

はい、Python 2でもまったく同じです。

d.values()

Python 3(ここでdict.values返すビュー代わり辞書の値を):

list(d.values())

3
@Muhd Pythonのドキュメントには常にすべてがあります:docs.python.org/2/library/stdtypes.html
jamylak

16
または、[d[k] for k in d]python2.xと3.xの両方で機能します実際にこれを使用することはお勧めしません)。通常、実際には値のリストは必要ないため、問題ありませんd.values()
mgilson 2013

2
少し「より良い」リンク(投稿したページの特定の場所へ): docs.python.org/2/library/stdtypes.html#dict.values
mgilson

1
またはd.itervalues()、ディクショナリ値のイテレータを返し、リストを回避します。
2015年

@figs質問は「値のリスト」ですが、Python 2でディクショナリを反復していた場合は間違いなく使用d.itervalues()し、ほとんどの場合、反復するだけでリストは必要ありません。
jamylak、2015年

25

*演算子を使用してdict_valuesを解凍できます。

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

またはリストオブジェクト

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

素敵な解決策、私はあなたがキーでこれを行うことができますが、値ではできないことを知っていました、知っておくと良いです:D
Timbus Calin

クールな新しい使用法* operator
jamylak

18

明確な方法は1つ(できれば1つだけ)あるべきです。

したがって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

結果

  1. 小さな辞書の方* operatorが速いです
  2. 重要な大きな辞書の場合list()は、おそらく少し速いです

1
list(L)、cuz「それを行うには、明白な方法が1つ(できれば1つだけ)あるべきです。」
Ufos

1
提案どおり変更、@ Ufos
Ronald Luc

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

-3
out: dict_values([{1:a, 2:b}])

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

純粋に視覚的な目的のため。有用な製品を生成しません...長い辞書を段落タイプのフォームで印刷する場合にのみ有用です。

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.