-1

Python 3.6

I have a list of dictionaries -

houses = ['a', 'b', 'c']
rarity_values = {'Common':0,'uncommon':0}
rarity = {}.fromkeys([i for i in houses],rarity_values) # creates dictionary of id

print(rarity)
# {'a': {'Common': 0, 'uncommon': 0}, 'b': {'Common': 0, 'uncommon': 0}, 'c': {'Common': 0, 'uncommon': 0}}

I'm going through a certain document and I want to count the number of times a common thing happens in each house. So if I see two Commons for house a and 1 uncommon for house b I get the result

# {'a': {'Common': 2, 'uncommon': 0}, 'b': {'Common': 0, 'uncommon': 1}, 'c': {'Common': 0, 'uncommon': 0}}

However, I'm noticing that when I increment the value for Common for any one house, it increments it for all of them.

print('a (before increment)',rarity['a']['Common'])
print('b (before increment)',rarity['b']['Common'])
rarity['b']['Common'] += 1
print('a (after increment)',rarity['a']['Common'])
print('b (after increment)',rarity['b']['Common'])

yields the output

a (before increment) 0
b (before increment) 0
a (after increment) 1
b (after increment) 1

instead of

a (before increment) 0
b (before increment) 0
a (after increment) 0
b (after increment) 1

Since I only incremented b by 1.

Or to see it better

{'a': {'Common': 1, 'uncommon': 0}, 'b': {'Common': 1, 'uncommon': 0}, 'c': {'Common': 1, 'uncommon': 0}}

which should have been

{'a': {'Common': 0, 'uncommon': 0}, 'b': {'Common': 1, 'uncommon': 0}, 'c': {'Common': 0, 'uncommon': 0}}

Does anyone know what I did wrong? Should I be nesting this differently?

Thanks

Micah Pearce
  • 1,805
  • 3
  • 28
  • 61

1 Answers1

1

You should use dictionary comprehension.

for i in houses:
    rarity[i] = dict(rarity_values)

In your original code, you are linking the same instance of rarity_values to each key 'a' and 'b'

Anthony Kong
  • 37,791
  • 46
  • 172
  • 304