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


i'm trying sort first item in list of tuples in value of dictionary.

here dictionary:

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

i want sorted output this:

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

i tried sorting values new dictionary, doesn't work:

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

d.values() return list of values present within dictionary. here want sort list present value corresponding key_ key. so, have call sorted function as:

# using tuple example 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), may directly sort list without calling sorted function as:

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

Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -