2014-09-12 61 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:也许不会是这样做的最有效的方式,但做这项工作