Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

'for statement' without colon

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))

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading