0

I'm learning how to use dictionaries currently and I sort of know how to do dictionary comprehension with for loops. However I want to include an if statement into the for loop. Something similar to this:

Dict = {}
for i in range(11):
    if i < 5:
        Dict[i] = 1
    else:
        Dict[i] = 0

How do I turn that mess into dictionary comprehension?

  • [Asking on Stack Overflow is not a substitute for doing your own research](https://meta.stackoverflow.com/q/261592/843953) This question has been answered many times on SO and covered in most decent tutorials on dict comprehensions. – Pranav Hosangadi Apr 18 '21 at 05:19

1 Answers1

3
Dict = {i: 1 if i < 5 else 0 for i in range(11)}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80