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?
You can actually speed the reversed case up a bit by doing sorted(a. keys(), reverse=True) instead of using the reversed() builtin.
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.
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 .
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With