+ 1

How to sort the dictionary values by length and key(both)?

D={0:'123###',1:'xyzcom',2:'aBcD',3:'sdgfhfhh',4:'xydhdg'} I want this to be like D={3:'sdgfhfhh',0:'123###',1:'xyzcom',4:'xydhdg'}

15th Oct 2019, 9:13 AM
Geek
Geek - avatar
6 ответов
15th Oct 2019, 9:41 AM
Trigger
Trigger - avatar
+ 3
I think this could be what you achieve: It's sorted by 2 criteria: first: length of value descending, second: value dic={0:'123###',1:'xyzcom',2:'aBcD',3:'sdgfhfhh',4:'xydhdg'} print(*sorted(dic.items(), key = lambda i : (-len(i[1]), i[1]))) # output: (3, 'sdgfhfhh'), (0, '123###'), (4, 'xydhdg'), (1, 'xyzcom'), (2, 'aBcD')
15th Oct 2019, 11:00 AM
Lothar
Lothar - avatar
+ 1
I have to print both index and value. If I sort the value alone, I will not know the index
15th Oct 2019, 9:38 AM
Geek
Geek - avatar
+ 1
Yes thanks for your help. I needed to print the first value. I modified your code. Can you tell is there any other way to do this? https://code.sololearn.com/cKaZ5XZVMFkW/?ref=app
15th Oct 2019, 10:36 AM
Geek
Geek - avatar
+ 1
Other than print(D.values()[0][1]) Im not sure
15th Oct 2019, 10:37 AM
Trigger
Trigger - avatar
+ 1
Ok thankyou
15th Oct 2019, 10:41 AM
Geek
Geek - avatar