简体   繁体   中英

Write values in a list of dictionaries

I am trying to loop over a list of dictionaries and write values to this specific dictionary:

from model.statistic_model import Sher, Op, Npp

TODAY = "today"
OVERALL = "overall"
SHER = "sherlock"
OP = "oprisk"
NPP = "npp"

popular_search_terms = {SHER: {TODAY: {}, OVERALL: {}}, OP: {TODAY: {}, OVERALL: {}}, NPP: {TODAY: {}, OVERALL: {}}}
engines = [Sher, Op, Npp]   
engines_container_overall = [popular_search_terms[SHER][OVERALL], popular_search_terms[OP][OVERALL], popular_search_terms[NPP][OVERALL]]

try:
    for index, engine in enumerate(engines):
        engines_container_overall[index] = df.get_popular_searchterms(False, engine)
except Exception as e:
    print(e)
    for index, engine in enumerate(engines):
        engines_container_overall[index] = pd.DataFrame()

When I access my list and print the following, I receive the values I want.

print(engines_container_overall[0])

But If i want to print the values of a specific dict, like popular_search_terms[SHER][OVERALL] , the value is none.

How can I successfully add data to a specific dictionary in my list?

You don't have to do it via the list. Python only saves a reference to the dictionary in the list. You can directly modify your dictionary with the update function.

Let's say

popular_search_terms = {SHER:{OVERALL:{"Test_SHER_overall":20}}}    
print(engines_container_overall[0])

produces {'Test_SHER_overall': 20}

Now update the dictionary

popular_search_terms[SHER][OVERALL].update({"Test_SHER_overall2":21})

and print(engines_container_overall[0]) produces {'Test_SHER_overall': 20, 'Test_SHER_overall2': 21}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM