Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of keys in dictionary

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?

like image 845
Qiao Avatar asked May 21 '11 18:05

Qiao


People also ask

What order are dictionary keys in?

As of Python 3.6, for the CPython implementation of Python, dictionaries maintain insertion order by default.

Does order of keys matter in dictionary Python?

Since dictionaries in Python 3.5 don't remember the order of their items, you don't know the order in the resulting ordered dictionary until the object is created. From this point on, the order is maintained. Since Python 3.6, functions retain the order of keyword arguments passed in a call.

How do you arrange the order of the dictionary?

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

Are dictionary values in order?

A dictionary in Python is a collection of items that stores data as key-value pairs. In Python 3.7 and later versions, dictionaries are sorted by the order of item insertion. In earlier versions, they were unordered.


2 Answers

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/

like image 173
ThiefMaster Avatar answered Sep 19 '22 05:09

ThiefMaster


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] 
like image 35
eduffy Avatar answered Sep 17 '22 05:09

eduffy