I'm trying to group together the binary strings of certain numbers based on how many 1's there are in the string.
This doesn't work:
s = "0 1 3 7 8 9 11 15"
numbers = map(int, s.split())
binaries = [bin(x)[2:].rjust(4, '0') for x in numbers]
one_groups = dict.fromkeys(range(5), [])
for x in binaries:
one_groups[x.count('1')] += [x]
The expected dictionary one_groups
needs to be
{0: ['0000'],
1: ['0001', '1000'],
2: ['0011', '1001'],
3: ['0111', '1011'],
4: ['1111']}
But I get
{0: ['0000', '0001', '0011', '0111', '1000', '1001', '1011', '1111'],
1: ['0000', '0001', '0011', '0111', '1000', '1001', '1011', '1111'],
2: ['0000', '0001', '0011', '0111', '1000', '1001', '1011', '1111'],
3: ['0000', '0001', '0011', '0111', '1000', '1001', '1011', '1111'],
4: ['0000', '0001', '0011', '0111', '1000', '1001', '1011', '1111']}
So far the only thing that has worked is if I use one_groups[x.count('1')] = one_groups.get(x.count('1')) + [x]
instead of one_groups[x.count('1')] += [x]
But why is that so? If I recall correctly, isn't dict[key]
supposed to return the value of that dictionary, similar to how dict.get(key)
works?
I've seen this thread Why dict.get(key) instead of dict[key]? but it didn't answer my question for this particular case, since I know for sure the program isn't meant to get the KeyError
I have also tried one_groups[x.count('1')].append(x)
but this doesn't work either.