Sushil Gurung Sushil Gurung - 7 months ago 17
Python Question

get value from one key in multiple dictionary python

This is the data i have in my

data.txt
file

{"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
setup
.

Thanks

Answer

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