如何在python3中将一个有组织的文件编入字典?

如何在python3中将一个有组织的文件编入字典?,python,string,python-3.x,dictionary,set,Python,String,Python 3.x,Dictionary,Set,我正在尝试创建此文件: c;f b;d a;c c;e d;g a;b e;d f;g f;d 变成这样一句话: {'e': {'d'}, 'a': {'b', 'c'}, 'd': {'g'}, 'b': {'d'}, 'c': {'f', 'e'}, 'f': {'g', 'd'}}. 我现在使用的代码如下所示: def read_file(file : open) -> {str:{str}}: f = file.read().rstrip('\n').split() answe

我正在尝试创建此文件:

c;f
b;d
a;c
c;e
d;g
a;b
e;d
f;g
f;d
变成这样一句话:

{'e': {'d'}, 'a': {'b', 'c'}, 'd': {'g'}, 'b': {'d'}, 'c': {'f', 'e'}, 'f': {'g', 'd'}}.
我现在使用的代码如下所示:

def read_file(file : open) -> {str:{str}}:
f = file.read().rstrip('\n').split()
answer = {}
for line in f:
    k, v = line.split(';')
    answer[k] = v
return answer
但是它给了我
{'f':'g','a':'c','b':'d','e':'d','c':'e','d':'g'}


如何修复它?

字典覆盖上一个键,请使用


但是我仍然有一个问题:dict类是可散列的,那么为什么我们不在所有的编码工作中使用默认dict呢?看起来默认dict更灵活。@编程驴子默认dict在一些用例中更灵活,在其他用例中更灵活。无论何时我们不需要有默认值,或者当我们没有特定的键时抛出错误,我们都不能使用默认dict。因此有一个强有力的理由,dict比默认dict更突出。
>>> import collections 
>>> answer = collections.defaultdict(set)
>>> for line in f: 
...     k, v = line.split(";")
...     answer[k].add(v)
... 
>>> answer
defaultdict(<class 'set'>, {'b': {'d'}, 'd': {'g'}, 'f': {'d', 'g'}, 'e': {'d'}, 'a': {'c', 'b'}, 'c': {'f', 'e'}})
>>> answer = {}
>>> for line in f:
...     k,v = line.split(";")
...     if k in answer:
...         answer[k].add(v)
...     else:
...         answer[k] = {v}
... 
>>> answer
{'b': {'d'}, 'd': {'g'}, 'f': {'d', 'g'}, 'e': {'d'}, 'a': {'c', 'b'}, 'c': {'f', 'e'}}