Sushil Gurung Sushil Gurung - 2 years ago 71
Python Question

get value from one key in multiple dictionary python

This is the data i have in my


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

using loop how would I be able to get only data from every


Answer Source

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, i.e.

{"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:
    return dicts_from_file

def get_setups(dicts):
    setups = []
    for dict in dicts:
        for key in dict:
            if key == "setup":
    return setups

print get_setups(dicts_from_file("data.txt"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download