I have a dictionary
{'a': 'first', 'b': 'second'}
However, I need the dictionary in a different order:
{'b': 'second', 'a': 'first'}
What is the best way to do this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Dictionaries are not ordered. So there is no way to do it.
If you have python2.7+, you can use collections.OrderedDict – in this case you could retrieve the item list using .items() and then reverse it and create a new OrderedDict from the reversed list:
>>> od = OrderedDict((('a', 'first'), ('b', 'second')))
>>> od
OrderedDict([('a', 'first'), ('b', 'second')])
>>> items = od.items() # list(od.items()) in Python3
>>> items.reverse()
>>> OrderedDict(items)
OrderedDict([('b', 'second'), ('a', 'first')])
If you are using an older python version you can get a backport from http://code.activestate.com/recipes/576693/
Method 2
Dictionaries don’t have order.
You can get the keys, order them however you like, then iterate the dictionary values that way.
keys = myDict.keys() keys = sorted(keys) # order them in some way for k in keys: v = myDict[k]
Method 3
You can’t; dicts are unsortable. Use an OrderedDict if you need an ordered dictionary.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0