python - 将dict添加到另一个dict

时间:2017-10-30 20:14:03

标签: python-3.x

需要将dict添加到另一个dict,但第二个位置需要是dinamic。

from time import gmtime, strftime

config = {}

def addStr(reason):
    datetime = strftime("%Y-%m-%d %H:%M:%S", gmtime());
    #config[reason] = {}  # uncoment here got error
    config[reason][datetime] = True
    return config

print ( addStr('reason1') )  # {'reason1': {'2017-10-30 20:08:26': True} }
time.sleep(10)
print ( addStr('reason1') ) # {'reason1': {'2017-10-30 20:08:26': True, '2017-10-30 20:08:36': True} }
time.sleep(10)
print ( addStr('reason1') ) # {'reason1': {'2017-10-30 20:08:26': True, '2017-10-30 20:08:36': True, '2017-10-30 20:08:46': True} }
time.sleep(10)
print ( addStr('reason2') ) # {'reason1': {'2017-10-30 20:08:26': True, '2017-10-30 20:08:36': True, '2017-10-30 20:08:46': True}, 'reason2': {'2017-10-30 20:08:56': True} }

我收到错误:

KeyError:'reason1'

1 个答案:

答案 0 :(得分:3)

如果我正确理解了您的问题,您希望自动创建缺失的密钥 为此,您需要使用collections.defaultdict

import collections
config = collections.defaultdict(dict)