Home > Mobile >  Read dictionary from file into original lists
Read dictionary from file into original lists

Time:10-13

I have one nested list, and one list for "numbers"

 test_keys = [["tobbe", "kalle"],["karl", "Clara"],["tobbe"],["tank"]]
 test_values = ['123', '234','345','456']

 res = {}
 for key in test_keys:
     for value in test_values:
         res[value] = key
         test_values.remove(value)
         break

 with open("myfile.txt", 'w') as f: 
     for key, value in res.items(): 
         f.write('%s;%s;\n' % (key, value))

This provides the file

123;['tobbe', 'kalle'];
234;['karl', 'Clara'];
345;['finis'];
456;['tank'];

now I want to load the data back into the a dictionary without the ";" and later on back into the corresponding lists.

CodePudding user response:

Try this:

res = {}

with open("myfile.txt") as file:
    for line in file:
        chunks = line.split(';')
        names = chunks[1][1:-1].split(', ')
        res[chunks[0]] = [name[1:-1] for name in names]

print(res)

test_keys = []
test_values = []

for key in res:
    test_keys.append(key)
    test_values.append(res[key])


print(test_keys)
print(test_values)
  • Related