Order of keys in dictionary
Asked Answered
M

3

29

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?

Mulish answered 21/5, 2011 at 18:11 Comment(9)
Ok, my fault, I'll read documentation. I just print it and it was out by specific order by chance. I thought it has something to do with a way it is written. Like php's array.Mulish
@Mulish This is actually a good question. I was like "oh, that'll be easy to answer with the documentation" -- it isn't. This "trivial fact" seems to be assumed knowledge in most places. The best I can find (in OrderedDict, chapter 8.3) is "An OrderedDict is a dict that remembers the order that keys were first inserted.".Trinity
Ahh, there it is: "It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary)." from 5.5 Data Structures in the Tutorial.Trinity
-1. Searching StackOverflow for "python dictionary order" easily finds the answer. You should at least try something before posting to StackOverflow.Sinasinai
possible duplicate of In what order does python display dictionary keys?Antihalation
@pst: Also Library Reference, Ch. 5 "Built-in Types": <quote>CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.</quote>Amicable
@Steven Rumbalski, I was looking for "how to change dictionary order?", not for "is it possible to change dictionary order?". They are different questions, though have the same answer.Mulish
@Qiao: If they have the same answer, then they're dupes. The idea is to get all the answers in one place.Amicable
possible duplicate of How to reverse order of keys in python dict?Postglacial
L
41

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/

Linkous answered 21/5, 2011 at 18:13 Comment(6)
Exactly, both dictionaries in your example are equivalent.Balakirev
Sorted and ordered are different thing. OrderedDict isn't sorted, can't be sorted manually and no data structure in Python is a sorted data structure (i.e. always automatically sorted).Rosie
That's what I meant. Edited my answer for clarity though.Linkous
@Roxy Oxymoron But an OrderedDict can be created from a sorted list. The question isn't: "how can I created a dict that is always sorted?"Trinity
Does not work in Python 3.4. The line items = od.items() returns an ItemsView object, which does not have a reverse() function.Diviner
Updated my answer to mention how to do it in Python 3.Linkous
F
8

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]
Frustule answered 21/5, 2011 at 18:13 Comment(1)
I think you wanted keys.sort(). sorted() returns a new list but does not modify the passed object.Linkous
B
4

You can't; dicts are unsortable. Use an OrderedDict if you need an ordered dictionary.

Banwell answered 21/5, 2011 at 18:13 Comment(2)
dict is sortable (you can always apply sorted to it) but the default order of keys cannot be influenced.Monadism
what if the keys are numeric & inserted incrementally eg:1,2,3,....10. So in this case, the order is preserved right?Diphase

© 2022 - 2024 — McMap. All rights reserved.