我米试图追加在Python中的字典键多个值

问题描述 投票:-1回答:1

我试图读取该文件,并将其转换成字典。经过阅读我必须采取一个单词,单词的第一个字符作为密钥,并且词本身的价值。如果用相同的字符另一个词来源于它应该在的值,以现有的密钥本身。

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
python python-3.x python-2.7 jupyter-notebook
1个回答
0
投票

只是简化了你的代码。有没有点在具有其他条件,如果使用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()
© www.soinside.com 2019 - 2024. All rights reserved.