-3

So I have a dict of numbers and strings, like so:

d = {"Hi": None, 2110: 1110, 1110: None}

And I want to print it right to left. Like this:

{1110: None, 2110: 1110, "Hi": None}

How would I go about doing this? If possible I would like to avoid sorting as the dict is already in order, just reverse order, and it seems to me it would take less time to just print it out in reverse than sort it. If I'm wrong, please correct me and sorting is then fine.

Ethan
  • 82
  • 1
  • 6

2 Answers2

0

You can use the code below to achieve this:

d = {"Hi": None, 2110: 1110, 1110: None}
print str(d)
print '{' + ','.join(str(d)[1:-1].split(',')[::-1]) + '}'

But actually dictionaries don't have any order at all and I think you maybe want to consider to use ordered dictionaries instead.

Ohumeronen
  • 1,769
  • 2
  • 14
  • 28
0

You would have to use OrderedDict from the collections module, and you're starting dictionary would have to be a list of tuples already ordered using OrderedDict, so you can preserve the order of the initial dictionary. This is needed as OrderedDict remembers the order of the keys that are inserted.

from collections import OrderedDict

d = OrderedDict([("Hi", None), (2110, 1110), (1110, None)])

result = OrderedDict(list(d.items())[::-1])
print(result)

Output:

OrderedDict([(1110, None), (2110, 1110), ('Hi', None)]) # remains this order always
RoadRunner
  • 25,803
  • 6
  • 42
  • 75