0

I have a list of dictionaries:

dicty = [defaultdict(list)] * (2)
dicty

[defaultdict(list, {}), defaultdict(list, {})]

Now I want to know how to index into these dictionaries?

I have tried:

dicty[0][0].append('abc')
dicty

[defaultdict(list, {0: ['abc']}), defaultdict(list, {0: ['abc']})]

But as you can see that it appends in both the dictionaries. I want to learn how to append into an individual dictionary.

el323
  • 2,760
  • 10
  • 45
  • 80

2 Answers2

2

You can use:

dicty = [defaultdict(list) for _ in range(2)]

When using [defaultdict(list)] * (2), all your dicts point to the same object in memory.

ettanany
  • 19,038
  • 9
  • 47
  • 63
1
from collections import defaultdict

""" Here, you are saying that you wish to add twice "defaultdict(list)".
    These are the same objects. You are just duplicating the same one with *
"""
dicty = [defaultdict(list)] * (2)
dicty[0][0].append('abc')
print dicty
print dicty[0] is dicty[1], '\n'

""" However, here : you are creating two distinct dictionnaries.
"""
dicty = []
for _ in range(2):
    dicty.append(defaultdict(list))
dicty[0][0].append('abc')
print dicty
print dicty[0] is dicty[1]

# outputs :
#[defaultdict(<type 'list'>, {0: ['abc']}), defaultdict(<type 'list'>, {0: ['abc']})]
#True 

#[defaultdict(<type 'list'>, {0: ['abc']}), defaultdict(<type 'list'>, {})]
#False
IMCoins
  • 3,149
  • 1
  • 10
  • 25