这是我在data.txt文件中的数据

{"setup": "test", "punchline": "ok", "numOfRatings": 0, "sumOfRatings": 0},
{"setup": "test2", "punchline": "ok2", "numOfRatings": 0, "sumOfRatings": 0}


我怎么能只从每个setup中获取数据?
字典使用循环?

谢谢

最佳答案

我不确定您是如何首先将字典添加到文本文件中的,但是如果可以的话,可以删除结尾的逗号,即

{"setup": "test", "punchline": "ok", "numOfRatings": 0, "sumOfRatings": 0}
{"setup": "test2", "punchline": "ok2", "numOfRatings": 0, "sumOfRatings": 0}


这样的事情可能适合您:

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"))

07-25 21:40