Python 3.x python-将dict添加到另一个dict

Python 3.x python-将dict添加到另一个dict,python-3.x,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

需要将一个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”

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


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


@乔伊登:直接分配将取代不改变。也就是说,您可以(以较小的性能代价)使用普通的
dict
setdefault
方法根据需要创建内部
dict
config.setdefault(reason,{})[datetime]=True
@ShadowRanger是的,我同意,如果使用相同的
键调用
函数
dict
setdefault
方法根据需要创建内部
dict
config.setdefault(reason,{})[datetime]=True
@ShadowRanger是的,我同意,如果使用相同的
键调用
函数
,则在更正后,他们希望如何添加到它们中
import collections
config = collections.defaultdict(dict)