2014-09-12 3 views
-3

사전 사전이 있습니다. dict의 각 키에는 두 개의 항목이 들어있는 목록이 있습니다. 하나는 다른 사전이고 다른 하나는 정수입니다.Python : 사전에서 상위 'n'키를 제거합니다.

dict = { 
    'hello' : [ 
     { 
     'blah' : 1, 
     'dodo' : 2 
     }, 
     3 
    ], 
    'world' : [ 
     { 
     'foo' : 7, 
     'bar' : 1 
     }, 
     8 
    ] 
} 

목록에서 두 번째 항목 인 정수에 사전 사전을 정렬하려고합니다. 그런 다음 사전에서 첫 번째 'n'키를 제거하십시오. 그것을 할 방법이 있습니까? 정렬 된 함수는 목록에서만 작동합니다. 여기

내가이의를 할 노력하고있어 기능입니다.

def create_inverted_index(inverted_index, corpus_tokens, corpus_files): 
for file_tokens in corpus_tokens: 
    file_id = corpus_files[file_tokens[0]] 
    for token in file_tokens[1]: 
     if token in inverted_index.keys(): 
      inverted_index[token][1] += 1 
      if file_id in inverted_index[token][0].keys(): 
       inverted_index[token][0][file_id] += 1 
      else: 
       inverted_index[token][0][file_id] = 1 
     else: 
      inverted_index[token] = [{file_id : 1}, 1] 
+0

당신의 실제 사전입니까? TypeError : unhashable type : 'list''를 실행할 때 실행됩니다. – Kevin

+0

@Kevin은 주요 dict에 대한 두 개의 키가 누락 된 것처럼 보입니다. – Nras

+0

작업 코드를 게시 할 수 있습니까? – khelwood

답변

3

이 작업을 수행하여 작업을 수행 할 수 있습니다

d = {1: [1, 2], 3: [2,4], 4:[3,3], 2:[4,1], 0:[5,0]} # dict to remove items from 

sorted_list=sorted(d.items(), key=lambda x: x[1][1]) 
sorted_keys = [key[1] for key in sorted_list] 

n=2 # number of items to remove 
for key in sorted_keys[0:n]: 
    d = dict([(k,v) for k,v in d.items() if v != key ]) 

이 코드를 복사 DICT를 DICT 값에서 두 번째 항목으로 정렬 목록에. 그런 다음 정렬 된 키만있는 목록을 작성하고이를 반복하여 사전에서 값으로 제거합니다. D 및 n=3 내 가치를

, 출력은 다음과 같습니다 N 들어

{3: [2, 4], 4: [3, 3]} 

= 2 :

{1: [1, 2], 3: [2, 4], 4: [3, 3]} 

시 :이 일을 가장 효율적인 방법이 될 수 있지만, 일을하지 않을 수 있습니다

1

파이썬에서 사전 주문을하지 않아도됩니다. dict을 정렬 할 수 없습니다. 그러나 collections.OrderedDict을 살펴볼 수 있습니다.

관련 문제