Another straightforward solution, which is guaranteed to work for Python v3.7 and over:
d = {'A':'a', 'B':'b', 'C':'c', 'D':'d'}
dr = {k: d[k] for k in reversed(d)}
print(dr)
Output:
{'D': 'd', 'C': 'c', 'B': 'b', 'A': 'a'}
Note that reversed dictionaries are still considered equal to their unreversed originals, i.e.:
(d == dr) == True
In response to someone upvoting this comment, I was curious to see which solution is actually faster.
As usual, it depends. Reversing a 10,000 item dictionary 10,000 times is faster with the solution using list
and reversed
on the items. But reversing a 1,000,000 item dictionary 100 times (i.e. the same number of items in total reversed dictionaries, just a bigger starting dictionary) is faster with the comprehension - it's left up to the reader to find the exact point where it flips. If you deal with large dictionaries, you may want to benchmark either if performance matters:
from random import randint
from timeit import timeit
def f1(d):
return dict(reversed(list(d.items())))
def f2(d):
return {k: d[k] for k in reversed(d)}
def compare(n):
d = {i: randint(1, 100) for i in range(n)}
print(timeit(lambda: f1(d), number=100000000 // n))
print(timeit(lambda: f2(d), number=100000000 // n))
compare(10000)
compare(1000000)
Results (one run, typical results):
4.1554735
4.7047593
8.750093200000002
6.7306311