Posts

Showing posts with the label dictionary

How to sort Dictionaries over values?

It is not possible to sort a dict, only to get a representation of a dict that is sorted. Dicts are inherently orderless, but other types, such as lists and tuples, are not. So we need a sorted representation, which will be a list—probably a list of tuples. Soln 1 : To sort on values : import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(1)) sorted_x will be a list of tuples sorted by the second element in each tuple.dict(sorted_x) == x To sort on keys : import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(0)) Soln 2 : x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted( x.items(), key=lambda a : a[1] )

What can be key of a dictionary?

Key of a dictionary can be : String Numbers tuples List can’t be a key of a dictionary and also tuple of list can’t be same. If we assign a tuple of list as key then it will generate a TypeError: unhashable type: 'list'.