我有这样的字典:
input = {9: { 3: 0.0003 , 2: 0.0002}, 8: {1: 100.0, 2: 50.0, 3: 300.0}}
输出必须是这样的:
output = {8: {2: 50.0, 1: 100.0, 3: 300.0}, 9: {2: 0.0002, 3: 0.0003}}
尝试了OrderedDict
,sorted
等,但仍然没有得到我想要的输出。
答案 0 :(得分:3)
请改用OrderedDict
,因为@timgeb提到字典在CPython3.6之前具有任意顺序:
from collections import OrderedDict
OrderedDict(sorted(d.items()))
OrderedDict([(8, {1: 100.0, 2: 50.0, 3: 300.0}), (9, {3: 0.0003, 2: 0.0002})])
答案 1 :(得分:1)
与sorted
一起使用 dict理解力两次:
>>> input = {9: { 3: 0.0003 , 2: 0.0002}, 8: {1: 100.0, 2: 50.0, 3: 300.0}}
>>> {k:dict(sorted(v.items())) for k,v in sorted(input.items())}
{8: {1: 100.0, 2: 50.0, 3: 300.0}, 9: {2: 0.0002, 3: 0.0003}}
>>>
对于2.7以下的python版本,请使用:
>>> input = {9: { 3: 0.0003 , 2: 0.0002}, 8: {1: 100.0, 2: 50.0, 3: 300.0}}
>>> dict([(k,dict(sorted(v.items()))) for k,v in sorted(input.items())])
{8: {1: 100.0, 2: 50.0, 3: 300.0}, 9: {2: 0.0002, 3: 0.0003}}
>>>
答案 2 :(得分:0)
您需要两次应用collectiobs.OrderedDict()
才能获得内部和外部排序的字典:
from collections import OrderedDict
from operator import itemgetter
data = {9: { 3: 0.0003 , 2: 0.0002}, 8: {1: 100.0, 2: 50.0, 3: 300.0}}
result = OrderedDict(
sorted(
(k, OrderedDict(sorted(v.items(), key=itemgetter(1))))
for k, v in data.items()
)
)
print(result)
哪个给:
OrderedDict([(8, OrderedDict([(2, 50.0), (1, 100.0), (3, 300.0)])), (9, OrderedDict([(2, 0.0002), (3, 0.0003)]))])
注意: OrderedDict
仅用于