How to create Python dictionary with multiple 'lists' for each key by reading from .txt file?
<p>I have a large text file that looks like:</p>

<pre><code>1   27  21  22
1   151 24  26
1   48  24  31
2   14  6   8
2   98  13  16
.
.
.
</code></pre>

<p>that I want to create a dictionary with. The first number of each list should be the key in the dictionary and should be in this format:</p>

<pre><code>{1: [(27,21,22),(151,24,26),(48,24,31)],
 2: [(14,6,8),(98,13,16)]}
</code></pre>

<p>I have the following code (with total points being the largest number in the first column of the text file (ie largest key in dictionary)):</p>

<pre><code>from collections import defaultdict

info = defaultdict(list)
filetxt = 'file.txt'
i = 1

with open(filetxt, 'r') as file:
    for i in range(1, num_cities + 1):
        info[i] = 0
    for line in file:
        splitLine = line.split()
        if info[int(splitLine[0])] == 0:
            info[int(splitLine[0])] = ([",".join(splitLine[1:])])
        else:
            info[int(splitLine[0])].append((",".join(splitLine[1:])))
</code></pre>

<p>which outputs</p>

<pre><code>{1: ['27,21,22','151,24,26','48,24,31'],
 2: ['14,6,8','98,13,16']}
</code></pre>

<p>The reason I want to do this dictionary is because I want to run a for loop through each "inner list" of the dictionary for a given key:</p>

<pre><code>for first, second, third, in dictionary:
   ....
</code></pre>

<p>I cannot do this with my current code because of the slightly different format of the dictionary (it expects 3 values in the for loop above, but receives more than 3), however it would work with the first dictionary format.</p>

<p>Can anyone suggest anyway to fix this?</p>

<pre><code>result = {}
with open(filetxt, 'r') as f:
    for line in f:
        # split the read line based on whitespace
        idx, c1, c2, c3 = line.split()

        # setdefault will set default value, if the key doesn't exist and
        # return the value corresponding to the key. In this case, it returns a list and
        # you append all the three values as a tuple to it
        result.setdefault(idx, []).append((int(c1), int(c2), int(c3)))
</code></pre>

<hr>

<p>Edit: Since you want to the key also to be an integer, you can <code>map</code> the <code>int</code> function over the split values, like this</p>

<pre><code>        idx, c1, c2, c3 = map(int, line.split())
        result.setdefault(idx, []).append((c1, c2, c3))
</code></pre>

python dictionary