Home > Blockchain >  How to create a dictionary of permutation values?
How to create a dictionary of permutation values?

Time:08-06

I need to assign 0 and 1 as values to keys in the dictionaries:

combinations_string_list = [num_list_to_str(i) for i in itertools.product([0, 1], repeat=2)]
all_stategy = []
for i in range(16):
    strategy_table = {x: y for x in combinations_string_list for y in [0, 1]}
    all_stategy.append(strategy_table)
print(all_stategy)

I got [{'00': 1, '01': 1, '10': 1, '11': 1}, {'00': 1, '01': 1, '10': 1, '11': 1}, {'00': 1, '01': 1, '10': 1, '11': 1}, ...] but I need [{'00': 0, '01': 0, '10': 0, '11': 0}, {'00': 0, '01': 0, '10': 0, '11': 1}, {'00': 0, '01': 0, '10': 1, '11': 0}, ...] instead. How can I create this kind of value? Thanks!

CodePudding user response:

You can zip the key sequence ["0", "1"] with each element of the cartesian product to produce input to dict:

>>> [dict(zip(["0", "1"], x)) for x in product([0,1], repeat=2)]
[{'0': 0, '1': 0}, {'0': 0, '1': 1}, {'0': 1, '1': 0}, {'0': 1, '1': 1}]

or

>>> values=[0,1]
>>> [dict(zip(map(str, values), x)) for x in product(values, repeat=2)]

CodePudding user response:

You can use itertools

[{'0':f'{x}', '1':f'{y}'} for x, y in itertools.product([0, 1],[0, 1])]

which gives us the expected output

[{'0': '0', '1': '0'}, {'0': '0', '1': '1'}, {'0': '1', '1': '0'}, {'0': '1', '1': '1'}]
  • Related