I currently have a line by line dictionary:
{'file1': 'txt'}
{'mydocument': 'pdf'}
{'file2': 'txt'}
{'archive.tar': 'gz'}
Is there a way to turn this into a one line dictionary? The outcome I would like:
{'file1': 'txt', 'mydocument': 'pdf', 'file2': 'txt', 'archive.tar': 'gz'}
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:
from ast import literal_eval
out = {}
with open("your_file.txt", "r") as f_in:
for line in map(str.strip, f_in):
if not line:
continue
for k, v in literal_eval(line).items():
out[k] = v
print(out)
Prints:
{'file1': 'txt', 'mydocument': 'pdf', 'file2': 'txt', 'archive.tar': 'gz'}