Home > Mobile >  Sorting of simple python dictionary for printing specific value
Sorting of simple python dictionary for printing specific value

Time:01-06

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?

CodePudding user response:

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'}

CodePudding user response:

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)])
a = dict(zip(pl, map('{:}'.format, range(1,len(pl)))))
  • Related