Pythonで辞書の値の一覧を取得する方法
Javaでは、Mapの値をListとして取得するのはlist = map.values();
を実行するのと同じくらい簡単です。私はPythonから辞書から値のリストを取得するための同様に簡単な方法があるのだろうかと思います。
small_ds = {x: str(x+42) for x in range(10)}
small_di = {x: int(x+42) for x in range(10)}
print('Small Dict(str)')
%timeit [*small_ds.values()]
%timeit list(small_ds.values())
print('Small Dict(int)')
%timeit [*small_di.values()]
%timeit list(small_di.values())
big_ds = {x: str(x+42) for x in range(1000000)}
big_di = {x: int(x+42) for x in range(1000000)}
print('Big Dict(str)')
%timeit [*big_ds.values()]
%timeit list(big_ds.values())
print('Big Dict(int)')
%timeit [*big_di.values()]
%timeit list(big_di.values())
Small Dict(str)
284 ns ± 50.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
401 ns ± 53 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Small Dict(int)
308 ns ± 79.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
428 ns ± 62.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Big Dict(str)
29.5 ms ± 13.8 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
19.8 ms ± 1.3 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Big Dict(int)
22.3 ms ± 1.4 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
21.2 ms ± 1.49 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
list()
の方が速い* operator
の方が速い以下の例に従ってください -
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))))
Dict_valuesを展開するには * operator を使用できます。
>>> d = {1: "a", 2: "b"}
>>> [*d.values()]
['a', 'b']
またはリストオブジェクト
>>> d = {1: "a", 2: "b"}
>>> list(d.values())
['a', 'b']