我试图读取该文件,并将其转换成字典。经过阅读我必须采取一个单词,单词的第一个字符作为密钥,并且词本身的价值。如果用相同的字符另一个词来源于它应该在的值,以现有的密钥本身。
import io
file1 = open("text.txt")
line = file1.read()
words = line.split()
Dict={}
for w in words:
if w[0] in Dict.keys():
key1=w[0]
wor=str(w)
Dict.setdefault(key1,[])
Dict[key1].append(wor)
else:
Dict[w[0]] = w
print Dict
只是简化了你的代码。有没有点在具有其他条件,如果使用set_default
words = 'hello how are you'.split()
dictionary = {}
for word in words:
key = word[0]
dictionary.setdefault(key, []).append(word)
print dictionary
为了摆脱set_default
使用default_dict
的
from collections import defaultdict
words = 'hello how are you'.split()
dictionary = defaultdict(list)
for word in words:
key = word[0]
dictionary[key].append(word)
print dictionary.items()