Home > OS >  creating a dictionary from a text file and getting values from using key as input
creating a dictionary from a text file and getting values from using key as input

Time:01-27

I am trying to create a dictionary from an existing text file but this should be done automatically so for example I have this text file

0 1
0 3
1 2

now I want to create this dictionary

a={
"0": "1","3"
"1": "0","2"}

which way should I follow to create this dictionary so when I add an input that is going to ask for a value that one is going to be the key and display the values?

I tried something with creating a list of all the keys and then adding the values from the text file but it only gives one value that is linked so for example it displays only

"0": "1"

and not

"0": "1","3"

CodePudding user response:

Use setdefault() to initialize each key to an empty list and append the value from that row.

a = {}

for line in file:
    key, value = line.split()
    a.setdefault(key, []).append(value)

print(a)

CodePudding user response:

You can try this:

from collections import defaultdict

a = defaultdict(list)
with open('text_file.txt', 'r') as f:
    for line in f:
        key, value = line.strip().split()
        a[key].append(value)
print(a)
  • Related