简体   繁体   中英

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. 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 . http://docs.python.org/2/library/collections.html#collections.namedtuple

OrderedDict keeps things in the order that you assigned them. 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.

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

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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