Python 如何从给定列表创建词典?
我正试图从给定的列表中创建一本词典,因为我知道该关键字将是该单词的第一个字母,并且具有相同第一个字母的关键字将相应地相加为一个关键字。你们能帮帮我吗Python 如何从给定列表创建词典?,python,dictionary,Python,Dictionary,我正试图从给定的列表中创建一本词典,因为我知道该关键字将是该单词的第一个字母,并且具有相同第一个字母的关键字将相应地相加为一个关键字。你们能帮帮我吗 words=[“苹果”、“圣经”、“鸟”、“糖果”、“日子”、“大象”、“朋友”] 一个更具Python风格的解决方案: import collections words= ['apple', 'bible','bird' ,'candy', 'day', 'elephant','friend'] d = collections.default
words=[“苹果”、“圣经”、“鸟”、“糖果”、“日子”、“大象”、“朋友”]
一个更具Python风格的解决方案:
import collections
words= ['apple', 'bible','bird' ,'candy', 'day', 'elephant','friend']
d = collections.defaultdict(list)
for w in words:
d[w[0]].append(w)
d = dict(d)
输出
{
"a": ["apple"],
"b": ["bible", "bird"],
"c": ["candy"],
"d": ["day"],
"e": ["elephant"],
"f": ["friend"],
}
只是另一种选择:
从集合导入defaultdict
单词=[“苹果”、“圣经”、“鸟”、“糖果”、“日子”、“大象”、“朋友”]
word_dict=defaultdict(lambda:[])
列表(映射(lambda-word:word_-dict[word[0]]。追加(word),words))
打印(dict(word_dict))
结果:
{'a': ['apple'], 'b': ['bible', 'bird'], 'c': ['candy'], 'd': ['day'], 'e': ['elephant'], 'f': ['friend']}
这回答了你的问题吗?您所说的“将相应地添加到一个键”是什么意思?你能展示一下你的预期结果吗?
{'a': ['apple'], 'b': ['bible', 'bird'], 'c': ['candy'], 'd': ['day'], 'e': ['elephant'], 'f': ['friend']}