Home > OS >  How do I access the keys and values of a dictionary read from a text file?
How do I access the keys and values of a dictionary read from a text file?

Time:01-30

I would like to test accessing the keys and values of a dictionary that is read from a text file. The goal is just to test out accessing them now but later I will want to match the values against a dataframe column and create a new column with the values that match. below is code and error message and what the dictionary looks like in the text file.

with open('dict_test.txt') as f:
    variable=f.read()

variable

for n in variable:
    print(n, variable[n])
TypeError                                 Traceback (most recent call last)
C:\Users\XXXXXX.py in <module>
      5 
      6 for n in variable:
----> 7     print(variable[n])
      8 
      9 # var2 = map(lambda x: x.replace("'", "").replace(",", "").strip(), variable)# understand map and strip

TypeError: string indices must be integers

this is what the dictionary in the text file looks like:

{"Delay one": ["this delay happens often", "this delay happens sometimes"], "Delay two": ["this delay happens almost alot", "this delay happens almost never"], "Other": ["this delay happens sometimes"]}

CodePudding user response:

You are currently reading the file as just a string (basically plain text). You'll need to parse the text into an actual dictionary that you can later access and manipulate. There are a variety of ways to do this in Python, including the built-in json module using the json.load method.

CodePudding user response:

That is not a Python dictionary even though it looks like it. Best thing to do is to save your txt file as json, and then deserialize it. I recommend reading about json serialization and deserialization. Here is the code that should work for you:

import json

#DESERIALIZING JSON
#load() - use this to load a JSON file into python
filename = 'filename.json'
with open(filename,'r') as read_file:
        to_python = json.load(read_file)
        print(to_python)
  •  Tags:  
  • Related