简体   繁体   English

如何在python中重新排列字典

[英]how to rearrange a dictionary in python

dictionary = {(1,1):[(2,2),[(3,3),(4,4)],5]}

dictionary[(2,2)] = [(3,3),[(4,4),(5,5)],6]

dictionary[(3,3)] = [(4,4),[(5,5),(6,6)],7]

print dictionary

Above code gives output as: 上面的代码给出的输出为:

{(3, 3): [(4, 4), [(5, 5), (6, 6)], 7], (1, 1): [(2, 2), [(3, 3), (4, 4)], 5], (2, 2): [(3, 3), [(4, 4), (5, 5)], 6]}

But, I wanted the output in order as input provided ie, 但是,我希望输出按顺序提供,即,

{(1,1):[(2,2),[(3,3),(4,4)],5],(2,2):[(3,3),[(4,4),(5,5)],6],(3,3):[(4,4),[(5,5),(6,6)],7]}

How can I rearrange the dictionary? 如何重新排列字典?

You should use OrderedDict from https://docs.python.org/2/library/collections.html 您应该使用https://docs.python.org/2/library/collections.html中的 OrderedDict

A normal python Dictonary is not ordered at all. 完全不订购普通的python字典。

You need to use an ordered dictionary instead of normal dictionary like this: 您需要使用有序词典而不是普通词典,如下所示:

from collections import OrderedDict

my_dict = OrderedDict()

my_dict[(1,1)] = [(2,2), [(3,3), (4,4)], 5]
my_dict[(2,2)] = [(3,3), [(4,4), (5,5)], 6]
my_dict[(3,3)] = [(4,4), [(5,5), (6,6)], 7]

print(my_dict)
# Output: OrderedDict([((1, 1), [(2, 2), [(3, 3), (4, 4)], 5]), ((2, 2), [(3, 3), [(4, 4), (5, 5)], 6]), ((3, 3), [(4, 4), [(5, 5), (6, 6)], 7])])

print(my_dict[(1, 1)])
# Output: [(2, 2), [(3, 3), (4, 4)], 5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM