简体   繁体   English

在字典列表中写入值

[英]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.但是,如果我想打印特定字典的值,例如popular_search_terms[SHER][OVERALL] ,则该值为无。

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. Python 只在列表中保存对字典的引用。 You can directly modify your dictionary with the update function.您可以使用update功能直接修改您的字典。

Let's say比方说

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

produces {'Test_SHER_overall': 20}产生{'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}print(engines_container_overall[0])产生{'Test_SHER_overall': 20, 'Test_SHER_overall2': 21}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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