Reversed method of Python dictionary

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:

# 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:

Dictionary printed in forward Order:

r 124

g 234

b 126

Dictionary printed in reverse Order:

b 126

g 234

r 124


Copyright 2024 © pythontic.com