0

I have a text file which has data like

{"0":{"Name":"ABC","Age":30,"City":"XYZ"},"1":{"Name":"LMN","Age":20,"City":"PQR"}}

I want to import this text file and read the dictionary.

file = open('text_file.txt','r')

dictn = eval(file.read())

print(dictn)

this code. But not getting correct result.

Can anyone tell me how to read this sort of file which has double dictionary in it using Python.

Thank you in advance

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
Anirudha.I
  • 43
  • 5

4 Answers4

0

What you see is a JSON file, you can simply use:

import json

with open('text_file.txt','r') as file:
    dictn = json.load(file)
print(dictn)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
0

That is a JSON Object and you can read it with:

import json

data = json.load(open('text_file.txt', 'r'))
JAntunes
  • 41
  • 1
  • 3
0

You can, also, use literal_eval from ast module instead of using eval which is not safe.

This is an example of how you can do it:

from ast import literal_eval as le

with open("new_data", 'r') as fp:
    data = le(fp.read())

print(data)

Output:

{'0': {'Age': 30, 'City': 'XYZ', 'Name': 'ABC'}, '1': {'Age': 20, 'City': 'PQR', 'Name': 'LMN'}}
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43
0

You can also use the yaml library from pyyaml:

import yaml

with open('text_file.txt', 'r') as f:
    dictn = f.read()
    print(dictn)
    print(type(dictn))
    result = yaml.load(dictn)
    print(result)
    print(type(result))
Nurjan
  • 5,889
  • 5
  • 34
  • 54