I currently have a line by line dictionary:
JavaScript
x
5
1
{'file1': 'txt'}
2
{'mydocument': 'pdf'}
3
{'file2': 'txt'}
4
{'archive.tar': 'gz'}
5
Is there a way to turn this into a one line dictionary? The outcome I would like:
JavaScript
1
2
1
{'file1': 'txt', 'mydocument': 'pdf', 'file2': 'txt', 'archive.tar': 'gz'}
2
I’m new to Python and a little lost how to do it to a dictionary.
Advertisement
Answer
Based on the comments, here is version that reads lines from a file and converts them to one dictionary:
JavaScript
1
12
12
1
from ast import literal_eval
2
3
out = {}
4
with open("your_file.txt", "r") as f_in:
5
for line in map(str.strip, f_in):
6
if not line:
7
continue
8
for k, v in literal_eval(line).items():
9
out[k] = v
10
11
print(out)
12
Prints:
JavaScript
1
2
1
{'file1': 'txt', 'mydocument': 'pdf', 'file2': 'txt', 'archive.tar': 'gz'}
2