除非字典存在,如何初始化字典

时间:2019-05-07 16:35:22

标签: python

我想创建一个嵌套字典。而且我只会在不存在字典的情况下初始化它。

dict_main = {}
lis = [1, 2]
for a in range(2):
    for i in range(2):
        if not isinstance(dict_main[i], dict): #This line IS ONLY FOR DEMO, IT DOES NOT WORK
            dict_main[i] = {}
            dict_main[i]['a'] = lis[a]
        else:
            dict_main[i]['a'] = max(lis[b], dict_main[i]['a'])
print(dict_main)

我知道这段代码并没有多大意义,但这只是为了说明自己。

我希望我的问题很清楚。

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以尝试检查字典中是否存在该键。

dict_main = {}
lis = [1, 2]
for a in range(2):
    for i in range(2):
        if i not in dict: #Checks if the key is contain on the dict, and if not, create it.
            dict_main[i] = {}
        if 'a' not in dict_main[i]:
            dict_main[i]['a'] = lis[a]
        else:
            dict_main[i]['a'] = max(lis[b], dict_main[i]['a'])
print(dict_main)