Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse order of keys in python dict?

This is my code :

a = {0:'000000',1:'11111',3:'333333',4:'444444'}  for i in a:     print i 

it shows:

0 1 3 4 

but I want it to show:

4 3 1 0 

so, what can I do?

like image 915
zjm1126 Avatar asked Mar 28 '11 06:03

zjm1126


People also ask

How do you reverse the order of a key in Python?

You can actually speed the reversed case up a bit by doing sorted(a. keys(), reverse=True) instead of using the reversed() builtin.

How do you reverse key values in a dictionary?

Use items() to Reverse a Dictionary in Python Printing a dictionary using items() will output an iterable list of tuple values that we can manipulate using the for loop for dictionaries. Reverse the key-value pairs by looping the result of items() and switching the key and the value.

How do I iterate a dictionary in reverse order?

Another simple solution to iterate over a dictionary in the sorted order of keys is to use the dict. keys() with the sorted() function. Alternatively, to iterate in reverse order of keys, you can specify the reverse argument of the sorted() function as True .

How do you reverse a dictionary element in Python?

1) Using OrderedDict() and items() method Later you make use of a reversed() function which is an in-built python method that takes an argument as the sequence data types like tuple, lists, dictionaries, etc and returns the reverse of it. Remember that reversed() method does not modify the original iterator.


1 Answers

The order keys are iterated in is arbitrary. It was only a coincidence that they were in sorted order.

>>> a = {0:'000000',1:'11111',3:'333333',4:'444444'} >>> a.keys() [0, 1, 3, 4] >>> sorted(a.keys()) [0, 1, 3, 4] >>> reversed(sorted(a.keys())) <listreverseiterator object at 0x02B0DB70> >>> list(reversed(sorted(a.keys()))) [4, 3, 1, 0] 
like image 159
SingleNegationElimination Avatar answered Sep 18 '22 08:09

SingleNegationElimination