Scalahansolo
Scalahansolo

Reputation: 3015

Simple file to dictionary

So I have the file below with the following values. What I am trying to do is to put these int values into a dictionary.

0  0   
0  1
0  2
0  3
0  4
1  1
1  2
1  3
1  4
1  5
2  3
2  4
3  3
4  5
5  0

I want my dictionary to look something along the lines of...

graph = {0: [0,1,2,3,4],1: [1,2,3,4,5], 2: [3,4] .... and so on.

I am currently using code from the following question.

Python - file to dictionary?

But it is not doing exactly what I was hoping. Any help would be great.

Upvotes: 0

Views: 182

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

Use collections.defaultdict:

>>> from collections import defaultdict
>>> d = defaultdict(list)
with open('input.txt') as f:
    for line in f:
        k, v = map(int, line.split())
        d[k].append(v)


>>> d
defaultdict(<type 'list'>,
{0: [0, 1, 2, 3, 4],
 1: [1, 2, 3, 4, 5],
 2: [3, 4], 3: [3],
 4: [5],
 5: [0]})

With normal dict you can use [dict.setdefault][2]:

with open('input.txt') as f:
    for line in f:
        k, v = map(int, line.split())
        d.setdefault(k, []).append(v)

Upvotes: 2

Related Questions