파이썬에서 사전 키를 목록으로 반환하는 방법은 무엇입니까?
Python 2.7 에서는 사전 키 , 값 또는 항목 을 목록으로 가져올 수 있습니다 .
>>> newdict = {1:0, 2:0, 3:0}
>>> newdict.keys()
[1, 2, 3]
이제 Python> = 3.3 에서 다음과 같은 결과를 얻습니다.
>>> newdict.keys()
dict_keys([1, 2, 3])
따라서 목록을 얻으려면 이렇게해야합니다.
newlist = list()
for i in newdict.keys():
newlist.append(i)
Python 3 에서 목록을 반환하는 더 좋은 방법이 있는지 궁금합니다 .
시도해보십시오 list(newdict.keys())
.
그러면 dict_keys
개체가 목록으로 변환 됩니다.
다른 한편으로, 그것이 중요한지 스스로에게 물어봐야합니다. 파이썬적인 코딩 방법은 오리 타이핑을 가정하는 것입니다 ( 오리처럼 보이고 오리처럼 꽥꽥 거리는 경우 오리입니다 ). dict_keys
객체는 대부분의 목적에 대한 목록과 같은 역할을합니다. 예를 들면 :
for key in newdict.keys():
print(key)
분명히 삽입 연산자는 작동하지 않을 수 있지만 어쨌든 사전 키 목록에는 그다지 의미가 없습니다.
Python> = 3.5 대안 : 목록 리터럴로 압축 해제 [*newdict]
새로운 압축 풀기 일반화 (PEP 448) 가 Python 3.5와 함께 도입되어 이제 다음을 쉽게 수행 할 수 있습니다.
>>> newdict = {1:0, 2:0, 3:0}
>>> [*newdict]
[1, 2, 3]
언 패킹 은 반복 가능한 모든 객체 와 함께 *
작동 하며, 사전이 반복 될 때 키를 반환하므로 목록 리터럴 내에서 목록을 사용하여 쉽게 목록을 만들 수 있습니다.
.keys()
ie를 추가하면 [*newdict.keys()]
의도를 좀 더 명시 적으로 만드는 데 도움이 될 수 있지만 함수 조회 및 호출 비용이 발생합니다. (정직하게 말하면 정말 걱정 해야 할 것이 아닙니다 ).
*iterable
구문은 수행과 유사 list(iterable)
과 그 동작은 처음에 기록 된 통화 섹션 파이썬 참조 설명서의. PEP 448에서는 *iterable
표시 될 수 있는 위치에 대한 제한 이 완화되어 목록, 집합 및 튜플 리터럴에도 배치 할 수있게되었습니다. Expression 목록 의 참조 설명서 도이를 설명하도록 업데이트되었습니다.
비록 동등 list(newdict)
더 빨리 (적어도 작은 사전에) 어떤 함수 호출이 실제로 수행되지 않기 때문에 있다는 차이로 :
%timeit [*newdict]
1000000 loops, best of 3: 249 ns per loop
%timeit list(newdict)
1000000 loops, best of 3: 508 ns per loop
%timeit [k for k in newdict]
1000000 loops, best of 3: 574 ns per loop
더 큰 사전을 사용하면 속도는 거의 동일합니다 (큰 컬렉션을 반복하는 오버 헤드가 함수 호출의 작은 비용보다 우선 함).
비슷한 방식으로 튜플과 사전 키 세트를 만들 수 있습니다.
>>> *newdict,
(1, 2, 3)
>>> {*newdict}
{1, 2, 3}
튜플 케이스의 후행 쉼표에주의하십시오!
list(newdict)
works in both Python 2 and Python 3, providing a simple list of the keys in newdict
. keys()
isn't necessary. (:
A bit off on the "duck typing" definition -- dict.keys()
returns an iterable object, not a list-like object. It will work anywhere an iterable will work -- not any place a list will. a list is also an iterable, but an iterable is NOT a list (or sequence...)
In real use-cases, the most common thing to do with the keys in a dict is to iterate through them, so this makes sense. And if you do need them as a list you can call list()
.
Very similarly for zip()
-- in the vast majority of cases, it is iterated through -- why create an entire new list of tuples just to iterate through it and then throw it away again?
This is part of a large trend in python to use more iterators (and generators), rather than copies of lists all over the place.
dict.keys()
should work with comprehensions, though -- check carefully for typos or something... it works fine for me:
>>> d = dict(zip(['Sounder V Depth, F', 'Vessel Latitude, Degrees-Minutes'], [None, None]))
>>> [key.split(", ") for key in d.keys()]
[['Sounder V Depth', 'F'], ['Vessel Latitude', 'Degrees-Minutes']]
You can also use a list comprehension:
>>> newdict = {1:0, 2:0, 3:0}
>>> [k for k in newdict.keys()]
[1, 2, 3]
Or, shorter,
>>> [k for k in newdict]
[1, 2, 3]
Note: Order is not guaranteed on versions under 3.7 (ordering is still only an implementation detail with CPython 3.6).
Converting to a list without using the keys
method makes it more readable:
list(newdict)
and, when looping through dictionaries, there's no need for keys()
:
for key in newdict:
print key
unless you are modifying it within the loop which would require a list of keys created beforehand:
for key in list(newdict):
del newdict[key]
On Python 2 there is a marginal performance gain using keys()
.
If you need to store the keys separately, here's a solution that requires less typing than every other solution presented thus far, using Extended Iterable Unpacking (python3.x+).
newdict = {1: 0, 2: 0, 3: 0}
*k, = newdict
k
# [1, 2, 3]
╒═══════════════╤═════════════════════════════════════════╕
│ k = list(d) │ 9 characters (excluding whitespace) │
├───────────────┼─────────────────────────────────────────┤
│ k = [*d] │ 6 characters │
├───────────────┼─────────────────────────────────────────┤
│ *k, = d │ 5 characters │
╘═══════════════╧═════════════════════════════════════════╛
참고URL : https://stackoverflow.com/questions/16819222/how-to-return-dictionary-keys-as-a-list-in-python
'your programing' 카테고리의 다른 글
현재 버전과 마지막 버전의 차이점을 찾으십니까? (0) | 2020.10.02 |
---|---|
Bash 스크립트에서 특정 조건이 발생하면 전체 스크립트를 종료하려면 어떻게해야합니까? (0) | 2020.10.02 |
스캐너가 next () 또는 nextFoo ()를 사용한 후 nextLine ()을 건너 뛰나요? (0) | 2020.10.02 |
정수의 최대 값 및 최소값 (0) | 2020.10.02 |
Java에서 equals 및 hashCode를 재정의 할 때 고려해야 할 문제는 무엇입니까? (0) | 2020.10.02 |