Wie kann ich eine Liste der Werte in einem Diktum in Python erhalten?
In Java ist das Abrufen der Werte einer Map als Liste so einfach wie das Ausführen von list = map.values();
. Ich frage mich, ob es in Python eine ähnlich einfache Möglichkeit gibt, eine Liste von Werten aus einem Diktat zu erhalten.
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()
schneller* operator
schnellerSie können den Operator * verwenden, um dict_values zu entpacken:
>>> d = {1: "a", 2: "b"}
>>> [*d.values()]
['a', 'b']
oder Listenobjekt
>>> d = {1: "a", 2: "b"}
>>> list(d.values())
['a', 'b']
Folgen Sie dem Beispiel unten -
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))))