Python: Reverse order of dictionary?

Viewed 91

I want to reverse the order of a string i.e. If i have:

dictionaryA = {'A':'a', 'B':'b', 'C':'c', 'D':'d'}

i want to rearrange it to where it's:

{'D':'d','C':'c', 'B':'b', 'A':'a'}

Why won't splicing work? ([::-1])? And reverse() too? How can you rearrange the order of each dictionary entry?

1 Answers

A very straightforward solution (although it's unclear why you'd need it):

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'}
Related