2014-09-12 99 views
-3

我有一個字典字典。對於字典中的每個鍵,都有一個列表,其中有兩個項目。一個是另一個字典,另一個是整數。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 2014-09-12 13:02:45

+0

@Kevin似乎是缺少主字典的兩個鍵。 – Nras 2014-09-12 13:04:56

+0

您可以發佈工作代碼嗎? – khelwood 2014-09-12 13:05:47

回答

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 ]) 

這段代碼複製字典由第二項字典值排序列表。然後它創建一個只有已排序的鍵的列表並迭代它,將它們作爲字典中的值刪除。

對於我的d和n=3值,輸出是:

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

對於n = 2:

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

PS:也許不會是這樣做的最有效的方式,但做這項工作