Programing

Python-dict에서 처음 N 개의 키 : 값 쌍 반환

lottogame 2020. 10. 26. 07:40
반응형

Python-dict에서 처음 N 개의 키 : 값 쌍 반환


다음 사전을 고려하십시오. d :

d = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

d (이 경우 N <= 4)에서 처음 N 개의 키 : 값 쌍을 반환하고 싶습니다. 이를 수행하는 가장 효율적인 방법은 무엇입니까?


a dict는 어떤 키가 먼저 삽입되었는지 기억하지 못 하기 때문에 "처음 n"키와 같은 것은 없습니다.

당신이 얻을 수 있는 n 개의 키 - 값 쌍 생각을 :

n_items = take(n, d.iteritems())

이것은의 구현 사용 take로부터 itertools조리법 :

from itertools import islice

def take(n, iterable):
    "Return first n items of the iterable as a list"
    return list(islice(iterable, n))

온라인 작업보기 : ideone


Python 3.6 용 업데이트

n_items = take(n, d.items())

무엇이든 검색하는 매우 효율적인 방법은 목록 또는 사전 이해를 슬라이싱과 결합하는 것입니다. 항목을 주문할 필요가없는 경우 (단지 n 개의 임의 쌍을 원함) 다음과 같이 사전 이해를 사용할 수 있습니다.

# Python 2
first2pairs = {k: mydict[k] for k in mydict.keys()[:2]}
# Python 3
first2pairs = {k: mydict[k] for k in list(mydict)[:2]}

일반적으로 이와 같은 이해는 "for x in y"루프보다 항상 실행 속도가 더 빠릅니다. 또한 .keys ()를 사용하여 사전 키 목록을 만들고 해당 목록을 분할하면 새 사전을 빌드 할 때 불필요한 키를 '건드리지'않도록 할 수 있습니다.

키 (값만)가 필요하지 않은 경우 목록 이해를 사용할 수 있습니다.

first2vals = [v for v in mydict.values()[:2]]

키를 기준으로 정렬 된 값이 필요한 경우에는 그다지 문제가되지 않습니다.

first2vals = [mydict[k] for k in sorted(mydict.keys())[:2]]

또는 키가 필요한 경우 :

first2pairs = {k: mydict[k] for k in sorted(mydict.keys())[:2]}

파이썬의 dict는 순서가 지정되지 않았으므로 "처음 N"키를 요청하는 것은 의미가 없습니다.

collections.OrderedDict즉 당신이 필요하다면 클래스를 사용할 수 있습니다. 처음 네 가지 요소를 다음과 같이 효율적으로 얻을 수 있습니다.

import itertools
import collections

d = collections.OrderedDict((('foo', 'bar'), (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')))
x = itertools.islice(d.items(), 0, 4)

for key, value in x:
    print key, value

itertools.islice반복기에서 요소 조각을 느리게 가져올 수 있습니다. 결과를 재사용 할 수있게하려면 다음과 같이 목록이나 다른 것으로 변환해야합니다.

x = list(itertools.islice(d.items(), 0, 4))

foo = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
iterator = iter(foo.items())
for i in range(3):
    print(next(iterator))

기본적으로 뷰 (dict_items)를 반복자로 전환 한 다음 next ()로 반복합니다.


여기서 보지 못했어요. 정렬되지는 않지만 사전에서 일부 요소를 가져와야하는 경우 가장 간단한 구문입니다.

n = 2
{key:value for key,value in d.items()[0:n]}

사전 정렬에 대해서는 PEP 0265참조하십시오 . 그런 다음 앞서 언급 한 반복 가능한 코드를 사용합니다.

정렬 된 키-값 쌍에서 더 많은 효율성이 필요한 경우. 다른 데이터 구조를 사용하십시오. 즉, 정렬 된 순서와 키-값 연결을 유지하는 것입니다.

import bisect

kvlist = [('a', 1), ('b', 2), ('c', 3), ('e', 5)]
bisect.insort_left(kvlist, ('d', 4))

print kvlist # [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]

이것은 귀하의 경우 '가장 효율적인'것이 무엇인지에 달려 있습니다.

If you just want a semi-random sample of a huge dictionary foo, use foo.iteritems() and take as many values from it as you need, it's a lazy operation that avoids creation of an explicit list of keys or items.

If you need to sort keys first, there's no way around using something like keys = foo.keys(); keys.sort() or sorted(foo.iterkeys()), you'll have to build an explicit list of keys. Then slice or iterate through first N keys.

BTW why do you care about the 'efficient' way? Did you profile your program? If you did not, use the obvious and easy to understand way first. Chances are it will do pretty well without becoming a bottleneck.


You can approach this a number of ways. If order is important you can do this:

for key in sorted(d.keys()):
  item = d.pop(key)

If order isn't a concern you can do this:

for i in range(4):
  item = d.popitem()

Dictionary maintains no order , so before picking top N key value pairs lets make it sorted.

import operator
d = {'a': 3, 'b': 2, 'c': 3, 'd': 4}
d=dict(sorted(d.items(),key=operator.itemgetter(1),reverse=True))
#itemgetter(0)=sort by keys, itemgetter(1)=sort by values

Now we can do the retrieval of top 'N' elements:, using the method structure like this:

def return_top(elements,dictionary_element):
    '''Takes the dictionary and the 'N' elements needed in return
    '''
    topers={}
    for h,i in enumerate(dictionary_element):
        if h<elements:
            topers.update({i:dictionary_element[i]})
    return topers

to get the top 2 elements then simply use this structure:

d = {'a': 3, 'b': 2, 'c': 3, 'd': 4}
d=dict(sorted(d.items(),key=operator.itemgetter(1),reverse=True))
d=return_top(2,d)
print(d)

For Python 3 and above,To select first n Pairs

n=4
firstNpairs = {k: Diction[k] for k in list(Diction.keys())[:n]}

consider a dict

d = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

from itertools import islice
n = 3
list(islice(d.items(),n))

islice will do the trick :) hope it helps !


just add an answer using zip,

{k: d[k] for k, _ in zip(d, range(n))}

This might not be very elegant, but works for me:

d = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

x= 0
for key, val in d.items():
    if x == 2:
        break
    else:
        x += 1
        # Do something with the first two key-value pairs

참고URL : https://stackoverflow.com/questions/7971618/python-return-first-n-keyvalue-pairs-from-dict

반응형