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?
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With