python字典中的索引超出范围

python字典中的索引超出范围,python,Python,我正在尝试实现一个字典,其中键中有一个数字,您可以在此处使用: 对词典进行排序: 字典无法排序,但我们可以使用排序后的键、值对或仅键或仅值列表: In [25]: dic={1: [10, 30], 2: [30], 3: [5,50]} In [26]: sorted(dic.items(),key=lambda x:sum(x[1])) #sort based on sum of lists Out[26]: [(2, [30]), (1, [10, 30]), (3, [5, 50])]

我正在尝试实现一个字典,其中键中有一个数字,您可以在此处使用:

对词典进行排序:

字典无法排序,但我们可以使用排序后的
键、值
对或仅
或仅
列表:

In [25]: dic={1: [10, 30], 2: [30], 3: [5,50]}

In [26]: sorted(dic.items(),key=lambda x:sum(x[1])) #sort based on sum of lists
Out[26]: [(2, [30]), (1, [10, 30]), (3, [5, 50])]
现在,您可以使用
collections.orderedict
从上一个列表创建
orderedict
,因为它保留了插入键的顺序:

In [27]: from collections import OrderedDict

In [30]: od=OrderedDict(sorted(dic.items(),key=lambda x:sum(x[1])))

In [31]: od
Out[31]: OrderedDict([(2, [30]), (1, [10, 30]), (3, [5, 50])])

a
是一个空列表,任何索引都将超出范围如何遍历此词典?例如,如果我想根据列表中元素的总和对其进行排序。
In [19]: dic={}  #use {} for declaring a new dict

In [20]: for _ in xrange(4):
   ....:     h,j=map(int,raw_input().split())
   ....:     dic.setdefault(h,[]).append(j)
   ....:     
1 10
1 20
2 30
3 5

In [21]: dic
Out[21]: {1: [10, 20], 2: [30], 3: [5]}
In [25]: dic={1: [10, 30], 2: [30], 3: [5,50]}

In [26]: sorted(dic.items(),key=lambda x:sum(x[1])) #sort based on sum of lists
Out[26]: [(2, [30]), (1, [10, 30]), (3, [5, 50])]
In [27]: from collections import OrderedDict

In [30]: od=OrderedDict(sorted(dic.items(),key=lambda x:sum(x[1])))

In [31]: od
Out[31]: OrderedDict([(2, [30]), (1, [10, 30]), (3, [5, 50])])