Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permutations of dictionary in python

I have a dictionary like this -

{'A': 0, 'B': 0, 'C': 0, 'D': 4}

I want to generate a list like this -

[{'A': 1, 'B': 0, 'C': 0, 'D': 4},
 {'A': 0, 'B': 1, 'C': 0, 'D': 4},
 {'A': 0, 'B': 0, 'C': 1, 'D': 4},
 {'A': 0, 'B': 0, 'C': 0, 'D': 5}]

What is the most pythonic way to do this?

like image 927
Narabhut Avatar asked Jul 01 '26 21:07

Narabhut


1 Answers

You can use list comprehension and dictionary comprehension together, like this

d = {'A': 0, 'B': 0, 'C': 0, 'D': 4}
print [{key1: d[key1] + (key1 == key) for key1 in d} for key in d]

Output

[{'A': 1, 'B': 0, 'C': 0, 'D': 4},
 {'A': 0, 'B': 0, 'C': 1, 'D': 4},
 {'A': 0, 'B': 1, 'C': 0, 'D': 4},
 {'A': 0, 'B': 0, 'C': 0, 'D': 5}]

The idea is to generate a new dictionary for each key, and when the key matches the key of the dictionary being constructed with dictionary comprehension, then add 1 to it. (key1 == key) will evaluate to 1 only when both the keys match, otherwise it will be zero.

like image 179
thefourtheye Avatar answered Jul 04 '26 09:07

thefourtheye