Вопрос

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?

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top