0

I have a file from which I need to extract the particular dictionary value

Data is in below format in file:

{'name': 'xyz', 'age': 14, 'country': 'india'}

My code:

var = 'country'
with open('abc.txt', 'r') as fw:
    first_line = fw.readline()
    dictvalue = first_line[var]
    print(dictvalue)

But this is not fetching value : india, it is throwing error: string indices must be integer

codeholic24
  • 955
  • 4
  • 22

2 Answers2

2

Because first_line=fw.readline() returns string, not dict. You can convert string to dict, using ast module:

import ast

var='country'
with open('abc.txt','r') as fw:
    first_line=fw.readline()
    dictvalue= ast.literal_eval(first_line)[var]
    print(dictvalue)

Also you would need to format your file, because india should be in within single quote

{'name': 'xyz','age': 14,'country': 'india'}

Output:

india

Convert a String representation of a Dictionary to a dictionary

codeholic24
  • 955
  • 4
  • 22
vszholobov
  • 2,133
  • 1
  • 8
  • 23
1

in this line of code,

first_line=fw.readline()

first_line is read as string ie., "{'name':'xyz','age':14,'country':'india'}"

Solution 1: You can make use of eval.

mydict = eval(first_line)
print(mydict[var])
#'india'

This works, but you should avoid using eval and exec functions, because it is considered as "dangerous" function in python. You can refer this for more on this topic.

Solution 2 (Recommended): Use Json module to read/write dict objects.

 import json
 data = {'name':'xyz','age':14,'country':'india'}

 #save dict as 'abc.txt' file. alternately use 'abc.json' to save as JSON file.
 json.dump(data, open('abc.txt','w'))

read_data = json.load(open('abc.txt', 'r'))
print (read_data)
#{'name': 'xyz', 'age': 14, 'country': 'india'}
RG_RG
  • 349
  • 5
  • 8