简体   繁体   中英

Sorting according to Second Element of Tuples in Lists in a Dictionary

Now I have the following dictionary containing lists, with tuples being elements of each list:

dict1 = {'it': [('was', 4)], 'was': [('the', 4)], 'the': [('best', 1), ('worst', 1), ('age', 2)], 'best': [('of', 1)], 'of': [('times', 2), ('wisdom', 1), ('foolishness', 1)], 'times': [('it', 2)], 'worst': [('of', 1)], 'age': [('of', 2)], 'wisdom': [('it', 1)]}

I need to sort the dictionary according to the frequencies of each value (Second element of each tuple) using dictionary comprehension . The expected output is:

{'it': ['was'], 'was': ['the'], 'the': ['age', 'best', 'worst'], 'best': ['of'], 'of': ['times', 'wisdom', 'foolishness'], 'times': ['it'], 'worst': ['of'], 'age': ['of'], 'wisdom': ['it']}

I tried with the following code:

dict2 = {k:sorted([pair[0] for pair in v],key=lambda x: x[1],reverse=True) for k,v in dict1.items()}

but the output turns out to be:

{'it': ['was'], 'was': ['the'], 'the': ['worst', 'age', 'best'], 'best': ['of'], 'of': ['foolishness', 'times', 'wisdom'], 'times': ['it'], 'worst': ['of'], 'age': ['of'], 'wisdom': ['it']}

The orders of values of keys 'the' and 'of' are mixed up. How should I correct my code?

You're quite close, but you seem to be filtering out the tuples, and then using a key function, which is redundant. Also, you are keeping only the words prior to sorting, so really what you're doing there is sorting based on the second character of those words, since now your iterable in each call to the key function is the actual string. This might make it clearer:

test = [('1z', 2), ('2a', 1), ('3d', 1)]
sorted([pair[0] for pair in test], key=lambda x: x[1])
# ['2a', '3d', '1z']

You could just sort the list of tuples and order based on the second items times -1 :

{k: [i[0] for i in sorted(v, key=lambda x: -x[1])] for k,v in d.items()}
{'it': ['was'],
 'was': ['the'],
 'the': ['age', 'best', 'worst'],
 'best': ['of'],
 'of': ['times', 'wisdom', 'foolishness'],
 'times': ['it'],
 'worst': ['of'],
 'age': ['of'],
 'wisdom': ['it']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM