sparrow sparrow - 5 months ago 18
Python Question

Sort an item in a list of tuples in the values of a dictionary with Python

I'm trying to sort the first item in a list of tuples in the value of a dictionary.

Here is my dictionary:

d = {'key_': (('2', 'a'), ('3', 'b'), ('4', 'c'), ('1', 'd'))}

I want the sorted output to look like this:

d2 = {'key_': (('1', 'd'), ('2', 'a'), ('3', 'b'), ('4', 'c'))}

I tried sorting the values to a new dictionary, but that doesn't work:

d2 = sorted(d.values(), key=lambda x: x[0])


d.values() return the list of all the values present within the dictionary. But here you want to sort the list which is present as value corresponding to key_ key. So, you have to call the sorted function as:

# Using tuple as your example is having tuple instead of list
>>> d['key_'] = tuple(sorted(d['key_'], key=lambda x: x[0]))
>>> d
{'key_': (('1', 'd'), ('2', 'a'), ('3', 'b'), ('4', 'c'))}

Alternatively (not suggested), you may also directly sort the list without calling the sorted function as:

>>> d['key_'] = list(d['key_']).sort(key=lambda x: x[0])
{'key_': (('1', 'd'), ('2', 'a'), ('3', 'b'), ('4', 'c'))}