简体   繁体   中英

adding to nested dictionaries in python

i have a nested dictionary in the form of:

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

Now i need to add more sub dictionaries to this as my program runs. I do this:

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

As you can see, i try to the test if the key time_stamp already exists and if yes, update the value with the new data. If not i want to create the key time_stamp and assign it a inital value. However im getting a Key Error once the programm goes past the inital value (see top).

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

What I want in the end is something like this:

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

What am I doing wrong here?

You're getting the error because self.emoji_per_word[time_stamp] doesn't exist when time_stamp != 0 so you need to create the dictionary first before assigning values to it, like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM