我有一本字典如下。
cat .aws/config
[default]
region = us-east-1
output = None
我想通过考虑列表中的元素数量来对字典进行排序。那是my_d={"0":["code_5", "code_4", "code_10"],
"1":["code_1", "code_2", "code_3", "code_11"],
"2": ["code_7", "code_8"], "3": ["code_9"]}
有3个元素,所以应该在字典的第一位。因此我的输出应该如下。
"1": ["code_1", "code_2", "code_3"]
现在我想只得到字典的前两个键。所以,我的最终输出应该如下所示。
my_d = {"1":["code_1", "code_2", "code_3", "code_11"],
"0":["code_5", "code_4", "code_10"],
"2": ["code_7", "code_8"], "3": ["code_9"]}
我的文件非常大。所以我想在python中快速有效地实现这一点。请帮帮我!
答案 0 :(得分:1)
你可以这样试试
a =list(sorted(my_d.items(),key = lambda x:len(x[1]),reverse = True)[0:2]
print a
Out[94]:
[('1', ['code_1', 'code_2', 'code_3', 'code_11']),
('0', ['code_5', 'code_4', 'code_10'])]
In [95]: dict(a)
Out[95]:
{'0': ['code_5', 'code_4', 'code_10'],
'1': ['code_1', 'code_2', 'code_3', 'code_11']}
用一个词来表达你的答案
a =dict(list(sorted(my_d.items(),key = lambda x:len(x[1]),reverse = True))[0:2])
答案 1 :(得分:1)
正如评论中所指出的,dict中键的顺序无法保证,如果您需要,必须使用Python OrdredDict
collections
from collections import OrderedDict
x = OrderedDict(sorted(my_d.iteritems(), key=lambda x:len(x[1]), reverse=True))
这样新的字典x
将保留您要查找的顺序。
答案 2 :(得分:0)
以下解决方案对您的用例可能有点贵。这基本上是
my_d={"0":["code_5", "code_4", "code_10"], "1":["code_1", "code_2", "code_3", "code_11"],
"2": ["code_7", "code_8"], "3": ["code_9"]}
# Convert to array
k = list(my_d.items())
# Ascending sort
k.sort(key=lambda x: len(x[1]))
# Slice last two elements
k = k[-2:]
# Convert back to dictionary
dict = {}
for i in range(len(k)):
dict[k[i][0]] = k[i][1]
dict将包含所需的输出