dict에서 값 목록을 가져오려면 어떻게 해야 합니까?
Python에서 dict의 값 목록을 가져오려면 어떻게 해야 하나요?
Java에서는 Map의 값을 목록으로 가져오는 것이 매우 간단합니다.list = map.values();
Python에서도 마찬가지로 간단한 방법으로 dict에서 값 목록을 얻을 수 있는지 궁금합니다.
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']
그것을 할 수 있는 확실한 방법은 하나, 바람직하게는 하나뿐이어야 한다.
그러므로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)
인텔(R) Core(TM) i7-8650U CPU @ 1.90GHz에서 실행.
# Name Version Build
ipython 7.5.0 py37h24bf2e0_0
결과
- 작은 사전의 경우
* operator
더 빠르다 - 중요한 빅 딕셔너리용
list()
조금 더 빠를 수도 있습니다.
다음의 예를 따릅니다.
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))))
- 사전에서 특정 키의 값 목록을 가져옵니다.
가장 간단한 방법은 반복하여 이해를 사용하는 것입니다.list_of_keys
.한다면list_of_keys
키가 아닌 키가 포함됩니다.d
,.get()
method를 사용하여 기본값을 반환할 수 있습니다(None
디폴트로는 변경할 수 있습니다.
res = [d[k] for k in list_of_keys]
# or
res = [d.get(k) for k in list_of_keys]
대부분의 경우 Python에는 키 아래에 값을 가져올 수 있는 메서드가 내장되어 있습니다.itemgetter()
빌트인부터operator
모듈.
from operator import itemgetter
res = list(itemgetter(*list_of_keys)(d))
데모:
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]
- 사전 목록에서 동일한 키의 값 가져오기
여기서도 이해는 기능합니다(사전 목록에서 반복).매핑과 마찬가지로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
순수하게 시각적인 목적으로요.유용한 제품을 생산하지 않음...긴 사전을 문단 유형 양식으로 인쇄하려는 경우에만 유용합니다.
언급URL : https://stackoverflow.com/questions/16228248/how-can-i-get-list-of-values-from-dict
'programing' 카테고리의 다른 글
MySQLdb를 사용하여 커서를 닫아야 하는 경우 (0) | 2022.10.03 |
---|---|
Larabel Migration을 사용하여 타임스탬프 열의 기본값을 현재 타임스탬프로 설정하려면 어떻게 해야 합니까? (0) | 2022.10.03 |
Java 스크립트의 배열에서 하위 하위 개체의 키 값을 매핑하는 방법 (0) | 2022.10.03 |
일식이 시작되지 않음 - Java 가상 시스템을 찾을 수 없습니다. (0) | 2022.10.03 |
Javascript를 사용하여 DOM 요소를 대체하려면 어떻게 해야 합니까? (0) | 2022.10.03 |