0

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.

Community
  • 1
  • 1
Scalahansolo
  • 2,615
  • 6
  • 26
  • 43

1 Answers1

2

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)
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504