0

I have a dictionary that needs to create a key when the key first shows up and adds a value for it, later on, keeps updating the key with values by appending these values to the previous value(s), I am wondering how to do that.

outter_dict = defaultdict(dict)  
num_index = 100
outter_dict['A'].update({num_index: 1})
outter_dict['A'].update({num_index: 2})

2 will replace 1 as the value for key 100 of the inner dict of outter_dict, but ideally, it should look like,

'A': {100:[1,2]} 

UPDATE

outter_dict = defaultdict(list)
outter_dict['A'][1].append(2)

but I got

IndexError: list index out of range

if I do

dict['A'][1] = list()

before assign any values to 1, I got

IndexError: list assignment index out of range
daiyue
  • 7,196
  • 25
  • 82
  • 149

1 Answers1

2

You can use a collections.defaultdict:

from collections import defaultdict
d = defaultdict(list)
num_index = 100
d[num_index].append(1)
d[num_index].append(2)
print(dict(d))

Output:

{100: [1, 2]}

Regarding your most recent edit, you want to use defautldict(dict) and setdefault:

outter_dict = defaultdict(dict)
outter_dict["A"].setdefault(1, []).append(2)
print(dict(outter_dict))

Output:

{'A': {1: [2]}}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • How about when `d` is a `defaultdict(dict)`? – daiyue Nov 07 '17 at 15:26
  • @daiyue `defaultdict(dict)` will allow you to initialize a dictionary before hand and not have to worry about checking if a certain key exists in the subdictionary before each addition of a new key-value pair. – Ajax1234 Nov 07 '17 at 15:29
  • I tried to use `defaultdict(list)` as a nested dict, see my OP, but I got `IndexError: list index out of range` – daiyue Nov 07 '17 at 15:53
  • @daiyue please see my recent edit. – Ajax1234 Nov 07 '17 at 16:02