반응형
dict에서 값 목록을 얻으려면 어떻게해야합니까?
파이썬에서 dict의 값 목록을 어떻게 얻을 수 있습니까?
Java에서는 Map의 값을 List로 얻는 것이 수행하는 것만 큼 쉽습니다 list = map.values();. 파이썬에서 dict에서 값 목록을 얻는 비슷한 방법이 있는지 궁금합니다.
예. Python 2 에서도 똑같은 내용입니다 .
d.values()
에서 파이썬 3 (여기서 dict.values반환 보기 대신 사전의 값을) :
list(d.values())
* 연산자 를 사용 하여 dict_values의 압축을 풀 수 있습니다 .
>>> d = {1: "a", 2: "b"}
>>> [*d.values()]
['a', 'b']
또는 목록 객체
>>> d = {1: "a", 2: "b"}
>>> list(d.values())
['a', 'b']
Python3을 고려하면 무엇이 더 빠릅니까?
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))))
out: dict_values([{1:a, 2:b}])
in: str(dict.values())[14:-3]
out: 1:a, 2:b
시각적 인 목적으로 만 사용하십시오. 유용한 제품을 생산하지 않습니다 ... 긴 사전을 단락 유형 양식으로 인쇄하려는 경우에만 유용합니다.
참고 URL : https://stackoverflow.com/questions/16228248/how-can-i-get-list-of-values-from-dict
반응형
'development' 카테고리의 다른 글
| 포커스를받을 수있는 HTML 요소는 무엇입니까? (0) | 2020.04.15 |
|---|---|
| 타입 안전이란 무엇입니까? (0) | 2020.04.15 |
| if (a-b <0)와 if (a <b)의 차이점 (0) | 2020.04.15 |
| Django ORM에서 select_related와 prefetch_related의 차이점은 무엇입니까? (0) | 2020.04.15 |
| 여러 제약 조건이있는 일반적인 방법 (0) | 2020.04.15 |