如何从python中的多个字典中获取一个键的值?

时间:2016-05-05 05:26:45

标签: python loops dictionary

这是我data.txt档案

中的数据
{"setup": "test", "punchline": "ok", "numOfRatings": 0, "sumOfRatings": 0},
{"setup": "test2", "punchline": "ok2", "numOfRatings": 0, "sumOfRatings": 0}

我如何才能只获取每个setup中的数据 字典使用循环?

由于

4 个答案:

答案 0 :(得分:1)

我不确定你是如何将词典放到你的文本文件中的,但是如果可以删除尾随的逗号,即

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

答案 1 :(得分:1)

    f = open('data')
    for line in f:
        d = ast.literal_eval(line)[0]
        print d['setup']

对于此代码,您需要放置','在每一行之后因为ast.literal_eval(line)将行转换为元组。

如果你没有','在每个字典之后然后使用这个

f = open('data')
for line in f:
   d = ast.literal_eval(line)
   print d['setup']

答案 2 :(得分:1)

如果文件中的行是标准的dict字符串,则可以尝试此操作。

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

希望这可以帮到你。

答案 3 :(得分:1)

如果它是标准的dict字符串,请尝试:

with open(file,'r') as file_input:
    for line in file_input:
        print eval(line).get("setup")