reversed method of Python dictionary

The reversed method returns a reverse iterator for a given Python dictionary instance. The Python example creates a dictionary of rgb values and prints them in reverse order using the method reversed().

Dictionary Updated 17 Nov 2019 1 min read

Method Name

reversed

Method Signature

reversed(d)

Parameters

d – A dictionary object

Return Value

Returns a reverse iterator for the given dictionary object. The iterator type returned is dict_reversekeyiterator.

Overview

  • The method reversed() returns a reverse iterator for a given Python dictionary instance.

  • Using the returned reverse iterator the dictionary keys and values can be accessed in the reverse order.

Example

python
# Example Python program that uses the reverse iterator of a dictionary

# Create a Python dictionary of rgb values

color = {"r":124, "g":234, "b":126};

# Print the dictionary in regular order

print("Dictionary printed in forward Order:");

for c in color:

    print(c, color[c]);

# Print the dictionary in reverse order

print("Dictionary printed in reverse Order:");

for c in reversed(color):

    print(c, color[c]);

Output

Output
Dictionary printed in forward Order:

r 124

g 234

b 126

Dictionary printed in reverse Order:

b 126

g 234

r 124