我想测试访问从文本文件读取的dictionary
的keys
和value
。我们的目标只是现在测试访问它们,但稍后我将希望将值与dataframe
列相匹配,并使用匹配的values
创建一个新列。下面是代码和错误消息,以及字典在文本文件中的样子。
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:UsersXXXXXX.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
这就是文本文件中的字典的样子:
{"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"]}
您当前读取的文件只是一个字符串(基本上是纯文本(。您需要将文本解析为一个实际的字典,以便以后访问和操作。在Python中有多种方法可以做到这一点,包括使用json.load方法的内置json
模块。
这不是Python字典,尽管它看起来很像。最好的做法是将txt文件保存为json,然后对其进行反序列化。我建议阅读json序列化和反序列化的相关知识。以下是适用于您的代码:
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)