Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting of simple python dictionary for printing specific value

I have a python dictionary.

a = {'1':'saturn', '2':'venus', '3':'mars', '4':'jupiter', '5':'rahu', '6':'ketu'}
planet = input('Enter planet : ')
print(planet)

If user enteres 'rahu', dictionary to be sorted like the following

a = {'1':'rahu', '2':'ketu', '3':'saturn', '4':'venus', '5':'mars', '6':'jupiter' }
print('4th entry is : ')

It should sort dictionary based on next values in the dictionary. If dictionary ends, it should start from initial values of dictionary. It should print 4th entry of the dictionary, it should return

venus

How to sort python dictionary based on user input value?

like image 667
sam Avatar asked Sep 12 '26 19:09

sam


1 Answers

Your use of a dictionary is probably not ideal. Dictionaries are useful when the key has a significance and the matching value needs to be accessed quickly. A list might be better suited.

Anyway, you could do:

l = list(a.values())
idx = l.index(planet)
a = dict(enumerate(l[idx:]+l[:idx], start=1))

NB. the above code requires the input string to be a valid dictionary value, if not you'll have to handle the ValueError as you see fit.

Output:

{1: 'rahu', 2: 'ketu', 3: 'saturn', 4: 'venus', 5: 'mars', 6: 'jupiter'}
like image 194
mozway Avatar answered Sep 15 '26 07:09

mozway



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!