[英]How to get values of one key from multiple dictionaries in python?
This is the data I have in my data.txt
file 这是我的
data.txt
文件中的数据
{"setup": "test", "punchline": "ok", "numOfRatings": 0, "sumOfRatings": 0},
{"setup": "test2", "punchline": "ok2", "numOfRatings": 0, "sumOfRatings": 0}
How would I be able to get only data from every setup
in the dictionaries using a loop? 如何使用循环从字典中的每个
setup
中仅获取数据?
Thanks 谢谢
I'm not sure how you're getting the dictionaries into your text file in the first place, but if it's possible to drop the trailing commas, ie 我不确定您是如何首先将字典放入文本文件中,但是是否可以删除结尾的逗号,即
{"setup": "test", "punchline": "ok", "numOfRatings": 0, "sumOfRatings": 0}
{"setup": "test2", "punchline": "ok2", "numOfRatings": 0, "sumOfRatings": 0}
Something like this may work for you: 这样的事情可能适合您:
def dicts_from_file(file):
dicts_from_file = []
with open(file,'r') as inf:
for line in inf:
dicts_from_file.append(eval(line))
return dicts_from_file
def get_setups(dicts):
setups = []
for dict in dicts:
for key in dict:
if key == "setup":
setups.append(dict[key])
return setups
print get_setups(dicts_from_file("data.txt"))
f = open('data')
for line in f:
d = ast.literal_eval(line)[0]
print d['setup']
for this code you need to put ',' after every line because ast.literal_eval(line) convert line into a tuple. 对于此代码,您需要在每行之后加上“,”,因为ast.literal_eval(line)将行转换为元组。
and if you do not have ',' after every dict then use this 如果您没有','则在每个字典之后使用此
f = open('data')
for line in f:
d = ast.literal_eval(line)
print d['setup']
You can try this if the line in your file is standard dict string. 如果文件中的行是标准字典字符串,则可以尝试此操作。
def get_setup_from_file(file_name):
result = []
f = open(file_name, "r")
for line in f.xreadlines():
# or line_dict = json.loads(line)
line_dict = eval(line) # if line end witch ',', try eval(line[0:-1])
result.append(line_dict["setup"])
return result
Wish this can help you. 希望这对您有帮助。
if it is standard dict string, try this: 如果是标准字典字符串,请尝试以下操作:
with open(file,'r') as file_input:
for line in file_input:
print eval(line).get("setup")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.