Reputation: 1672
need to add a dict to another dict, but the 2nd position need to be 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} }
I'm Getting error:
KeyError: 'reason1'
Upvotes: 0
Views: 134
Reputation: 28266
If I understood your question correctly, you want the missing keys to be automatically created.
For that, you need to use a collections.defaultdict
import collections
config = collections.defaultdict(dict)
Upvotes: 3