Associating a name with each bit in a bitmask I have the following code:

dic = {}
bin_rep = [1 if digit == '1' else 0 for digit in bin(n)[2:]]
if len(bin_rep) &lt; size_bin:
    bin_rep += [0] * (size_bin - len(bin_rep))
# turn this into dictionnary - might all be done better?
for i in range(0, size_bin):
    dic[self.p.get_agents()[i]] = bin_rep[i]
return dic


Essentially, I'm taking an number n, turning it into a list (its binary representation, potentially padded with 0 up to size_bin), say:

[0 1 1 1 1 0 0 0 0 0 0]


From that padded list, I create a dictionary, where key==agent name and value==1/0, say:

{'a1':0, 'a2':1 ... 'an':0}


(The array as a whole corresponds to a team, the 0/1 represents the inclusion of an agent into the team. So each team corresponds to a binary array which can be represented as an int.)

The code works, using list and dictionary comprehension. However, would someone have a cleaner/smarter way to perform this? It's good if it's optimal, though not crucial, and would like to keep it readable.

I absolutely need to have the ultimate result into a dictionary because other parts of the code use that representation.

EDIT: using python 3.6
Suggestions


enumerate is built-in function useful here
dict comprehensions can be used to create dictionaries from arbitrary key and value expressions
imho '{:b}'.format(n) is easier to read than bin(n)[2:]
in additional you may use OrderedDict if you often iterate over agents 1, 2, 3, 4, ...


Final code (n = 10, size_bin =  6)

{'a{}'.format(k): int(v) for k, v in enumerate('{:b}'.format(10).ljust(6, '0'), start=1)}


and with full utilize format syntax

{'a{}'.format(k): int(v) for k, v in enumerate('{:&lt;0{}b}'.format(10, 6), start=1)}