Python:删除top';n';字典里的钥匙
我有一本字典词典。词典中的每个键都有一个列表,其中有两项。一个是另一个字典,另一个是整数Python:删除top';n';字典里的钥匙,python,sorting,dictionary,Python,Sorting,Dictionary,我有一本字典词典。词典中的每个键都有一个列表,其中有两项。一个是另一个字典,另一个是整数 dict = { 'hello' : [ { 'blah' : 1, 'dodo' : 2 }, 3 ], 'world' : [ { 'foo' : 7, 'bar' : 1 }, 8 ] } 我想根据列表中的第二项,即整数,对
dict = {
'hello' : [
{
'blah' : 1,
'dodo' : 2
},
3
],
'world' : [
{
'foo' : 7,
'bar' : 1
},
8
]
}
我想根据列表中的第二项,即整数,对字典dict进行排序。然后从字典中删除第一个“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]
在Python中,字典没有顺序。您不能对
dict
进行排序。不过,你可以看看 您可以这样做:
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
,输出为:
{3: [2, 4], 4: [3, 3]}
对于n=2:
{1: [1, 2], 3: [2, 4], 4: [3, 3]}
附言:这可能不是最有效的方法,但这项工作是你的实际任务吗?当我试图运行它时,我得到了
TypeError:unhabable type:'list'
。@凯文好像主目录的两个键不见了。你能发布工作代码吗?你说的“对字典排序”是什么意思?字典是无序的。dict
s不可排序。而且,您永远不应该给隐藏在内置代码后面的东西命名(也就是说,不要给它命名dict
),因为在Python3.7中,字典是有序的(但不一定是有序的)。