Sorting of simple python dictionary for printing specific value

Question:

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?

Asked By: sam

||

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'}
Answered By: mozway

If you need care about keys '1'..'6' and use planet variable I suggest the following:

pl = list(a.values())[list(a.values()).index(planet):]
pl.extend(list(a.values())[:list(a.values()).index(planet)])
dict(zip(map('{:}'.format, list(a.keys())), pl))

In case of planet='rahu' will produce the next stdout:

{'1': 'rahu', '2': 'ketu', '3': 'saturn', '4': 'venus', '5': 'mars', '6': 'jupiter'}
Answered By: storenth
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.