0

I am requesting clarification on the use of sorted lambda for sorting dictionaries. I have referenced these posts 1 2 in making my code which works fine, but am interested in understanding how it actually works.

'Unf': {'idf': 0, 'den': 0.0}, 
'Ale': {'idf': 3.1179499062782403, 'den': 0.0041841004184100415}, 
'No ': {'idf': 3.1179499062782403, 'den': 0.008620689655172414}, 
One': {'idf': 3.1179499062782403, 'den': 0.005319148936170213}, 
'but': {'idf': 0, 'den': 0.0}, 
'Bio': {'idf': 0, 'den': 0.0}, 
'Wen': {'idf': 0, 'den': 0.0}, 
'Lar': {'idf': 0, 'den': 0.0}, 
'Ana': {'idf': 0, 'den': 0.0}, 
'Adv': {'idf': 0, 'den': 0.0}}

this is the sorting code

newdict = dict(sorted(values.items(), key=lambda item: (item[1]['idf'], item[1]['den']), reverse=True))
newdict = dict(sorted(values.items(), key=lambda item: (item[1][0], item[1][1]), reverse=True))

for item: (item[1]['idf'], item[1]['den'] what exactly is the [1] index referring to? is it referring to the values(my inner dictionary) returned by values.items?

If so, if i change the index to [0] I would be getting the dictionary key instead? Additionally, how would I go about sorting this if I were to use operator.itemgetter instead?

Thank you very much for the help everyone!

Bob Tan
  • 103
  • 6

1 Answers1

0

turns out values.items() returns a dict item which is iterable, hence the ability to use an index on it.

Reference from: https://towardsdatascience.com/sorting-a-dictionary-in-python-4280451e1637

Bob Tan
  • 103
  • 6