How to create a list of values in a dictionary comprehension in Python

后端 未结 2 1932
太阳男子
太阳男子 2021-01-24 07:23

Taking a very simple example of looping over a sentence and creating a dictionary which maps {x:y}, where x is a key representing the length of the wor

相关标签:
2条回答
  • 2021-01-24 07:54

    Sure, you can, using sorted + groupby, but it doesn't look great.

    from itertools import groupby
    d = dict([(k, list(g)) for k, g in groupby(sorted(mywords.split(), key=len), key=len)])
    
    print(d)
    {2: ['be', 'be'],
     3: ['May', 'and'],
     4: ['your', 'your'],
     5: ['short'],
     6: ['coffee', 'strong', 'Monday']}
    

    P.S., Here's my answer (using defaultdict that I recommend over this) to the original question.

    0 讨论(0)
  • 2021-01-24 08:01

    Don't try to cram everything in one line, it won't be readable. This is a simple, easy-to-understand solution, even if it takes a couple of lines:

    from collections import defaultdict
    
    mywords = "May your coffee be strong and your Monday be short"    
    ans = defaultdict(list)
    
    for word in mywords.split():
        ans[len(word)].append(word)
    
    0 讨论(0)
提交回复
热议问题