Home > Software design >  Python dictionaries changing values in other dictionaries, bug?
Python dictionaries changing values in other dictionaries, bug?

Time:02-28

I'm getting output that I'm not expecting with this code:

class Band:
    zones = {}
class Zone:
    count = 0

global_zones = {}

global_zones[1] = Band()
global_zones[2] = Band()
global_zones[1].zones[3302] = Zone()
global_zones[2].zones[3302] = Zone()

print('b4 1/3302',global_zones[1].zones[3302].count)
print('b4 2/3302',global_zones[2].zones[3302].count)

global_zones[1].zones[3302].count  = 1

print('af 1/3302',global_zones[1].zones[3302].count)
print('af 2/3302',global_zones[2].zones[3302].count)

Output:

b4 1/3302 0
b4 2/3302 0
af 1/3302 1
af 2/3302 1

Expected Output:

b4 1/3302 0
b4 2/3302 0
af 1/3302 1
af 2/3302 0

Why is this happening? Thanks!

CodePudding user response:

class Band:
    def __init__(self):
        self.zones = {}
class Zone:
    def __init__(self):
        self.count = 0

global_zones = {}

global_zones[1] = Band()
global_zones[2] = Band()
global_zones[1].zones[3302] = Zone()
global_zones[2].zones[3302] = Zone()

print('b4 1/3302',global_zones[1].zones[3302].count)
print('b4 2/3302',global_zones[2].zones[3302].count)

global_zones[1].zones[3302].count  = 1

print('af 1/3302',global_zones[1].zones[3302].count)
print('af 2/3302',global_zones[2].zones[3302].count)

Thanks to @Barmar for the suggestion in the comments.

  • Related