如何将每个单词的第一个字母保存为带有相关单词的字典中的密钥?
list = ['pine', 'dinner', 'liver', 'love', 'pick']
输出:
dictionary = {'p' : ['pine', 'pick'], 'd' : ['dinner'], 'l' : ['love', 'liver']}
答案 0 :(得分:2)
使用默认Dict我们可以做到:
from collections import defaultdict
list_ = ['pine', 'dinner', 'liver', 'love', 'pick']
x = defaultdict(list)
for item in list_:
x[item[0]].append(item)
print(x)
# defaultdict(<class 'list'>, {'p': ['pine', 'pick'], 'd': ['dinner'], 'l': ['liver', 'love']})
然后,您可以像字典一样使用x
:
print(x['p'])
#['pine', 'pick']
答案 1 :(得分:2)
Dict = dict()
# iterate over the collection
for word in words:
# get the first letter
letter = word[0]
# the default value for key 'letter'
# will be an empty list
# if the key isn't present yet
# otherwise, nothing's changed
Dict.setdefault(letter, [])
# now you are sure that there's a list at that key
Dict[letter].append(word)
答案 2 :(得分:0)
我认为应该这样做。
dictionary = {}
list = ['pine', 'dinner', 'liver', 'love', 'pick']
for i in list:
if i[0] not in dictionary.keys():
dictionary[i[0]] = []
dictionary[i[0]].append(i)
答案 3 :(得分:0)
尝试:
list = ['pine', 'dinner', 'liver', 'love', 'pick']
d= dict()
for item1 in list:
li=[]
for item2 in list:
if item1[0]==item2[0]:
li.append(item2)
d[item1[0]]= li
print d