0

I'm trying to read a series of dictionaries from a file:

GFG.txt

{'geek': 10, 'geeky': True}
{'GeeksforGeeks': 'Education', 'geekgod': 101.0, 3: 'gfg'}
{'supergeek': 5}

and I found this website with the following solution:

import pickle
geeky_file = open('GFG.txt', 'r')
dictionary_list = pickle.load(geeky_file)
  
for d in dictionary_list:
    print(d)
geeky_file.close()

However this throws an exception:

TypeError: a bytes-like object is required, not 'str'

Opening the file in binary mode:

geeky_file = open('GFG.txt', 'rb')

gives me the error:

UnpicklingError: invalid load key, '{'.
HappyPy
  • 9,839
  • 13
  • 46
  • 68
  • 1
    you can load with pickle, if you have dumped with pickle. Who wrote that file format ? – azro Nov 02 '22 at 21:15
  • like @azro said, you can't just write the dictionaries in plain text in the file. you need to use pickle to dump the dictionaries to a file and then you can use pickle to load those dictionaries from a file – Omer Dagry Nov 02 '22 at 21:18
  • You could in theory read each line as JSON, but that is invalid JSON. The problem here is you don't use a standard file format. – ProblemsLoop Nov 02 '22 at 22:10

2 Answers2

0

If every "text dictionary" is on a single line, ast.literal_eval can help:

import ast

with open('GFG.txt', 'rb') as f:
    list_of_dicts = [ast.literal_eval(line.decode()) for line in f]
list_of_dicts

Output:

[{'geek': 10, 'geeky': True},
 {'GeeksforGeeks': 'Education', 'geekgod': 101.0, 3: 'gfg'},
 {'supergeek': 5}]
Tim
  • 248
  • 2
  • 7
0

Based this answer, you can load each dict in to a new dict to access them by line number.

import ast

file_dicts = {}
with open('GFG.txt') as f:
    for i, line in enumerate(f):
        file_dicts[i] = ast.literal_eval(line)

Result:

{0: {'geek': 10, 'geeky': True}, 1: {'GeeksforGeeks': 'Education', 'geekgod': 101.0, 3: 'gfg'}, 2: {'supergeek': 5}}
bn_ln
  • 1,648
  • 1
  • 6
  • 13