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?
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>
You can also read the full spec in the reference.
For generators, it's called generator expression, not generator comprehension.