-2

I have a question making a dictionary with text file.

I have a text file like this:

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

What I am trying to do,

I would like to make {0: [1,2,3], 1:[2,3,4], 2:[3,4,5]} like this

lists = {}
test = open('Test.txt', mode='r', encoding = 'utf-8').read().split('\n')

for i in test:
    if len(lists) == 0:
       lists[i.split(',')[0]] = [i.split(',')[1]]

In here, whenever I call for fuction, the value number is changed..

I am trying to figure out how I gotta do,

But it seems little bit tricky to me

Can anyone give me some advice or direction for it?

I really appreciate it

Thank you!

Matthias
  • 12,873
  • 6
  • 42
  • 48
NEWBIEOFPYTHONS
  • 85
  • 1
  • 1
  • 7

2 Answers2

2
result = {}

with open('test.txt') as f:
    for line in f:
        key, value = line.strip().split(',')
        if key not in result:
            result[key] = [value]
        else:
            result[key].append(value)

print(result)

Output:

{'0': ['1', '2', '3'], '1': ['2', '3', '4'], '2': ['3', '4', '5']}

You can also try the defaultdict collection which is more convinent.

Shi XiuFeng
  • 715
  • 5
  • 13
0

Here is an approach with a defaultdict. map with the reference to the int function is used to convert the strings to integers.

from collections import defaultdict

result = defaultdict(list)
with open('Test.txt', mode='r', encoding='utf-8') as infile:
    for line in infile:
        key, value = map(int, line.split(','))
        result[key].append(value)

print(result)

The result is

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

Besides the bonus of the default value it will behave like a normal dictionary.

Matthias
  • 12,873
  • 6
  • 42
  • 48