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?
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?
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/
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 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]
keys.sort()
. sorted()
returns a new list but does not modify the passed object. –
Linkous You can't; dict
s are unsortable. Use an OrderedDict
if you need an ordered dictionary.
dict
is sortable (you can always apply sorted
to it) but the default order of keys cannot be influenced. –
Monadism eg:1,2,3,....10
. So in this case, the order is preserved right? –
Diphase © 2022 - 2024 — McMap. All rights reserved.