0
test_keys = ["Rash", "Kil", "Varsha"]
test_values = [1, 4, 5]
  
# using dictionary comprehension
# to convert lists to dictionary
res = {test_keys[i]: test_values[i] for i in range(len(test_keys))}
  
# Printing resultant dictionary 
print ("Resultant dictionary is : " +  str(res))

above, there should be an ending colon " : " after 'for statement' like for i in range(3) :

but this line didn't put " : " at the end of range()
res = {test_keys[i]: test_values[i] for i in range(len(test_keys))}
This is totally out of syntax i knew, how this is possible?
perhaps is it syntax for dictionary only?

bbiot426
  • 37
  • 6
  • The colon `:` means that the following block of code refers to the line that contains that colon. However, in comprehensions, you don't need the colon. – zaibaq Apr 27 '22 at 12:21

3 Answers3

2

You can do it with sets, dictionaries, lists and generators and is called set, dictionary and list comprehension respectively or generator expression:

set_comprehension = {i for i in range(10)}
dict_comprehension = {i:i for i in range(10)}
list_comprehension = [i for i in range(10)]
generator_expression = (i for i in range(10))

print(set_comprehension)
print(dict_comprehension)
print(list_comprehension)
print(generator_expression)

Output:

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<generator object <genexpr> at 0x7fe9e8999dd0>
Nin17
  • 2,821
  • 2
  • 4
  • 14
  • You can also read the full spec in the [reference](https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries). – Jakob Stark Apr 27 '22 at 12:24
  • For generators, it's called *generator expression*, not *generator comprehension*. – mkrieger1 Apr 27 '22 at 12:30
0

What you have described is called "dictionary comprehension" and it's an alternative syntax for creating an iterable.

It comes in useful quite often.

Similar to list comprehension:

newlist = [expression for item in iterable if condition]
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Don
  • 164
  • 3
  • 1
    no it isn't, it's dictionary comprehension if it's in a dictionary – Nin17 Apr 27 '22 at 12:20
  • Spot on @Nin17. I'd gotten into a bad habit of using the same term for both. Thanks for pointing it out. – Don Apr 27 '22 at 12:25
0

In python, the : is used to indicate that this line we enter a new bloc of code (deeper level of indentation starting next line).
Ex:

if condition:
    pass #Deeper indentation
for i in range(10):
    pass #Deeper indentation
while True:
    pass #Deeper indentation
#And many others

In list comprehension everything is on the same line so the : is not required and will cause issue since the next line don't have deeper indentation.

Xiidref
  • 1,456
  • 8
  • 20