3

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?

8
  • 2
    What rules do you have? Some of the numbers in your 'permutations' seem to come from no-where. Commented Mar 31, 2014 at 6:47
  • Oh sorry, I should've said what is the most pythonic way to do this? Updated question to reflect this. Commented Mar 31, 2014 at 6:47
  • And the values in the permutations should be increased by 1 from the source one. Commented Mar 31, 2014 at 6:48
  • as @AlexThornton asked, where those 1s and 5 are coming from? Please provide full input and some explanation about rules. Commented Mar 31, 2014 at 6:49
  • 1
    Permutation means reorder elements, but your values just changed, value of each key in each step. It's not what you call permutation I'm afraid. Commented Mar 31, 2014 at 6:49

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Tim Thanks Removed that :) I was about write a normal loop based solution, but I got the comprehension idea. So, forgot to remove that :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.