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

别来无恙 提交于 2019-12-20 05:03:13

问题


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 words and y is a list of words in the sentence that contain x amount of letters

Input:

mywords = "May your coffee be strong and your Monday be short"

Expected Output:

{2: ['be', 'be'], 3: ['May', 'and'], 4: ['your', 'your'], 5: ['short'], 6: ['coffee', 'strong', 'Monday']}

Here's an attempt that creates a list of values but overwrites it each time:

{len(x):[x] for x in mywords.split()}
{2: ['be'], 3: ['and'], 4: ['your'], 5: ['short'], 6: ['Monday']}

Is it possible to do this in one line in Python?


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/46820714/how-to-create-a-list-of-values-in-a-dictionary-comprehension-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!