[英]How do I access the keys and values of a dictionary read from a text file?
I would like to test accessing the keys
and value
s of a dictionary
that is read from a text file.我想测试访问从文本文件中读取的
dictionary
的keys
和value
。 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.目标只是现在测试访问它们,但稍后我将希望将这些值与
dataframe
列进行匹配,并使用匹配的values
创建一个新列。 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"]}
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.在 Python 中有多种方法可以做到这一点,包括使用 json.load 方法的内置
json
模块。
That is not a Python dictionary even though it looks like it.那不是 Python 字典,即使它看起来像。 Best thing to do is to save your txt file as json, and then deserialize it.
最好的办法是将你的txt文件保存为json,然后反序列化。 I recommend reading about json serialization and deserialization.
我建议阅读有关 json 序列化和反序列化的信息。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.