How can I make an organized file into dictionary in python3?
<p>I'm trying to make the file:</p>

<pre><code>c;f
b;d
a;c
c;e
d;g
a;b
e;d
f;g
f;d
</code></pre>

<p>Into a dict like</p>

<pre><code>{'e': {'d'}, 'a': {'b', 'c'}, 'd': {'g'}, 'b': {'d'}, 'c': {'f', 'e'}, 'f': {'g', 'd'}}.
</code></pre>

<p>The code I'm using now is like below</p>

<pre><code>def read_file(file : open) -&gt; {str:{str}}:
f = file.read().rstrip('\n').split()
answer = {}
for line in f:
    k, v = line.split(';')
    answer[k] = v
return answer
</code></pre>

<p>But it gives me <code>{'f': 'g', 'a': 'c', 'b': 'd', 'e': 'd', 'c': 'e', 'd': 'g'}</code>
How can I fix it?</p>

<p>Dictionaries overwrite the previous key, Use a <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow">defaultdict here</a> </p>

<pre><code>&gt;&gt;&gt; import collections 
&gt;&gt;&gt; answer = collections.defaultdict(set)
&gt;&gt;&gt; for line in f: 
...     k, v = line.split(";")
...     answer[k].add(v)
... 
&gt;&gt;&gt; answer
defaultdict(&lt;class 'set'&gt;, {'b': {'d'}, 'd': {'g'}, 'f': {'d', 'g'}, 'e': {'d'}, 'a': {'c', 'b'}, 'c': {'f', 'e'}})
</code></pre>

<p>If you prefer the traditional approach, then you can add a <code>if</code> condition </p>

<pre><code>&gt;&gt;&gt; answer = {}
&gt;&gt;&gt; for line in f:
...     k,v = line.split(";")
...     if k in answer:
...         answer[k].add(v)
...     else:
...         answer[k] = {v}
... 
&gt;&gt;&gt; answer
{'b': {'d'}, 'd': {'g'}, 'f': {'d', 'g'}, 'e': {'d'}, 'a': {'c', 'b'}, 'c': {'f', 'e'}}
</code></pre>

python string python-3.x dictionary set