添加到python中的嵌套字典

时间:2018-05-28 12:55:05

标签: python dictionary nested

我有一个嵌套字典:

self.emoji_per_word = {0: {'worte': 0, 'emojis': 0, '#': 0}}

现在我需要在程序运行时添加更多的子词典。我这样做:

worte = 0

emoji = 0

# some code that assigns values to the 2 variables and creates the time_stamp variable

if time_stamp in self.emoji_per_word:
   self.emoji_per_word[time_stamp]['worte'] = self.emoji_per_word[time_stamp]['worte'] + worte
   self.emoji_per_word[time_stamp]['emojis'] = self.emoji_per_word[time_stamp]['emojis'] + emojis
else:
   self.emoji_per_word[time_stamp]['worte'] = worte
   self.emoji_per_word[time_stamp]['emojis'] = emojis

如您所见,如果密钥 time_stamp 已经存在,我会尝试进行测试,如果是,则使用新数据更新该值。如果不是,我想创建密钥 time_stamp 并为其分配一个初始值。但是,一旦程序超过初始值,我就会得到一个关键错误。(见上)。

Exception in thread Video 1:
Traceback (most recent call last):
  File "C:\Anaconda\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\MA\Code\jsonparser_v2\jsonparser_v2.py", line 418, in run
    self.process_json()
  File "C:\MA\Code\jsonparser_v2\jsonparser_v2.py", line 201, in process_json
    self.emoji_per_word[time_stamp]['worte'] = worte
KeyError: 1

我最终想要的是这样的:

self.emoji_per_word = {0: {'worte': 20, 'emojis': 5, '#':0.25}, 1: {'worte': 20, 'emojis': 5, '#':0.25}}  

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

您收到错误是因为self.emoji_per_word[time_stamp]time_stamp != 0不存在,所以您需要先为字典赋值,然后才能为其分配值,如下所示:

else:
    self.emoji_per_word[time_stamp] = {}
    self.emoji_per_word[time_stamp]['worte'] = worte
    self.emoji_per_word[time_stamp]['emojis'] = emojis