words = {'apple', 'plum', 'pear', 'peach', 'orange', 'cherry', 'quince'}
d = {}
for x in sorted(words):
if x not in d:
d[len(x)]=x
d[len(x)].append(x)
print(d)
AttributeError: 'str' object has no attribute 'append'
The goal of the program is to have a multiple keys, distinguished by word length (i.e., 4, 5, or 6 letters), that store alphabetized values:
{4: 'pear', 'plum' 5: 'apple', 'peach' 6: 'cherry', 'orange', 'quince'}
I am having issues adding items to a key. What I am currently getting as my output is (without the append line):
{4: 'plum', 5: 'peach', 6: 'quince'}
so it seems to be erasing the previous loops entry. The update and append commands are coming back with errors.
答案 0 :(得分:2)
您可以使用collections.defaultdict
创建一个字典,根据字符长度存储每个项目:
from collections import defaultdict
d = defaultdict(list)
words = {'apple', 'plum', 'pear', 'peach', 'orange', 'cherry', 'quince'}
for word in words:
d[len(word)].append(word)
final_data = {a:sorted(b) for a, b in d.items()}
输出:
{4: ['pear', 'plum'], 5: ['apple', 'peach'], 6: ['cherry', 'orange', 'quince']}
此外,itertools.groupby
可用于更短的解决方案:
import itertools
words = {'apple', 'plum', 'pear', 'peach', 'orange', 'cherry', 'quince'}
new_words = {a:sorted(list(b)) for a, b in itertools.groupby(sorted(words, key=len), key=len)}
输出:
{4: ['pear', 'plum'], 5: ['apple', 'peach'], 6: ['cherry', 'orange', 'quince']}
答案 1 :(得分:1)
你不能append
到一个字符串;你必须从头开始制作你的字典值list
。您还有两个检查,而不是一个:
试试这个:
size = len(x)
if size not in d:
d[size] = [x]
else:
d[size].append(x)