Home > Enterprise >  How to turn a dictionary written to a .txt file, into an actual dictionary in python
How to turn a dictionary written to a .txt file, into an actual dictionary in python

Time:08-22

I have a .txt file (test.txt) with an example dictionary written in it

{"1": "John", "2": "Jeremy", "3": "Jake"}

In python I'm trying to grab the dictionary from this text file, and use it as a dictionary in my program, but the class of the variable isn't a dictionary, it's the 'str' class.

dictionary = open("test.txt", mode="r")
print(dictionary)
print(type(dictionary)

Output:
{"1": "John", "2": "Jeremy", "3": "Jake"}
<class 'str'>

Just want to know how I can make this variable a dictionary instead of a string

Thanks

CodePudding user response:

I'm going to make a number of assumptions.

First, dictionary in your code is a file, not a string. You forgot the read. Second, the data in your file is NOT a valid dictionary. The names need to be quoted.

Assuming they are quoted, what you have is JSON. Use json.load:

Contents:

{ "1": "John", "2": "Jeremy", "3": "Jake" }

Code:

import json
dictionary = json.load(open('test.txt'))

CodePudding user response:

First of all you can't convert this string to a dictionary as its format isn't correct, it should be like this

dictionary = '{"1": "John", "2": "Jeremy", "3": "Jake"}'

notice how I added the names between the ""

For the conversion you will use json library

Full Code:

import json

dictionary = open("test.txt", mode="r").read()

conv = json.loads(dictionary)

print(conv)
print(type(conv))

This is the code I tested with:

import json

str = '{"1": "John", "2": "Jeremy", "3": "Jake"}'

conv = json.loads(str)

print(conv)
print(type(conv))

My might not work if you don't fix your .txt file.

  • Related