简体   繁体   English

python中的混乱字典输出

[英]Messy dictionary output in python

I'm trying to output some variables from a dictionary, but it doesn't output it in the order that I assigned. 我正在尝试从字典中输出一些变量,但是它没有按照我分配的顺序输出。 I know that dictionary has no order, but I need a dictionary for another purpose so I can't use a list. 我知道字典没有顺序,但是我需要字典用于其他目的,所以我不能使用列表。 I was wondering whether there is a way to make the output be at the same order that I assigned the values in the first place. 我想知道是否有一种方法可以使输出与我首先分配值的顺序相同。

Input: 输入:

a = {'Name': "a", 'Date': 20021501, 'Time': 1800, 'Type': "JK", 'TG': 68, 'DC': 98}

Output: 输出:

{'TG': 68, 'DC': 98, 'Time': 1800, 'Date': 20021501, 'Type': 'JK', 'Name': 'a'}

Thanks to any helper 感谢任何帮助者

Use an OrderedDict from the collections module. 使用来自collections模块的OrderedDict http://docs.python.org/2/library/collections.html#collections.OrderedDict http://docs.python.org/2/library/collections.html#collections.OrderedDict

If you don't need to modify the data, you could also consider a namedtuple . 如果您不需要修改数据,则也可以考虑namedtuple http://docs.python.org/2/library/collections.html#collections.namedtuple http://docs.python.org/2/library/collections.html#collections.namedtuple

OrderedDict keeps things in the order that you assigned them. OrderedDict使事物保持分配的顺序。 I don't often find that useful, but if that is what you need use it. 我并不经常发现它有用,但是如果您需要它,请使用它。

Alternatively, if you are not really using the "dictionary" access property, consider just storing a list of tuples, 2-tuples here, if you do not need to modify either member of the tuple. 另外,如果您并没有真正使用“字典”访问属性,那么,如果您不需要修改任何一个元组成员,请考虑只在此处存储一个元组列表,即2个元组。

a = [('Name', 'Joe'), ('Age, '10')]
for element in a:
   print 'key {0}, value {1}'.format (element [0], element [1])

Use an OrderedDict: http://docs.python.org/2/library/collections.html#collections.OrderedDict 使用OrderedDict: http : //docs.python.org/2/library/collections.html#collections.OrderedDict

Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. 顺序词典与常规词典一样,但是它们记住项目插入的顺序。 When iterating over an ordered dictionary, the items are returned in the order their keys were first added. 在有序字典上进行迭代时,将按照项的键首次添加的顺序返回项。

This subclass of OrderedDict will remember the order that entries were LAST inserted: OrderedDict的此子类将记住条目最后插入的顺序:

class LastUpdatedOrderedDict(OrderedDict):
    'Store items in the order the keys were last added'

    def __setitem__(self, key, value):
        if key in self:
            del self[key]
        OrderedDict.__setitem__(self, key, value)

That link also shows that you can take a normal dictionary, sort it, and store it in order as an OrderedDict. 该链接还显示您可以选择普通词典,对其进行排序,然后按顺序存储为OrderedDict。

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

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