Home > Back-end >  Adding a list as a value in a dictionary converts it into a string, I still want a list
Adding a list as a value in a dictionary converts it into a string, I still want a list

Time:09-20

I have a .txt file 'file.txt'. Keys are single strings of a country, to each of them is associated a value: a list of other countries.

My file is like this for every country in the world:

'united_states':['canada', 'mexico']
'mexico':['united_states', 'guatemala', 'belize']
'belize':['mexico', 'guatemala']
'guatemala':['mexico', 'belize', 'el_salvador', 'honduras']

I want to create a dictionary from the txt file. The keys in the txt file should be the keys in the dictionary and the values in the txt files should be the values in the dictionary.

I tried this (among other attempts which didn't output anything but errors)

with open('file.txt') as f:
    for line in f:
        line_cut = line.split(':')
        borders = {line_cut[0].replace("'", ''): line_cut[1]}

The issue is that it outputs me a single line as dictionary and the value becomes a string no matter what I do, it won't accept it as a list and I'd like it to output all lines in the pattern 'key':[values] so the ideal output should be


{'canada':['united_states', 'denmark']
'united_states':['canada', 'mexico']
'mexico':['united_states', 'guatemala', 'belize']
'belize':['mexico', 'guatemala']
'guatemala':['mexico', 'belize', 'el_salvador', 'honduras']}

I'm out of ideas. I just want to add a list as a value in a dictionary without it turning into a string and outputing only a single line.

CodePudding user response:

To load the data from the file to python dictionary you can try:

from ast import literal_eval

with open("file.txt", "r") as f_in:
    data = literal_eval("{"   ",".join(f_in)   "}")

print(data)

Prints:

{
    "united_states": ["canada", "mexico"],
    "mexico": ["united_states", "guatemala", "belize"],
    "belize": ["mexico", "guatemala"],
    "guatemala": ["mexico", "belize", "el_salvador", "honduras"],
}

CodePudding user response:

You should probably try to receive the file in a different format.

As it is, you can use something like this:

borders = dict()
with open('file.txt') as f:
    for line in f:
        delete_chars = ["'", '"', "[", "]", " ", "\n"]
        line_clean = line.translate(str.maketrans(
            {char: "" for char in delete_chars}))
        country, raw_neighborgs = line_clean.split(':')
        neighbors = [n for n in raw_neighborgs.split(",")]
        borders.update({country: neighbors})

    
  • Related