简体   繁体   中英

invalid syntax when trying to make a dictionary comprehension?

test_list_k = ['a', 'b', 'c', 'd']

test_list_v = ['f', 'g', 'h']

test_dict_comp = {k: v for k in test_list_k and for v in test_list_v}
print(test_dict_comp)

For some reason it counts the second for in test_dict_comp as invalid syntax.

Assuming the goal is to make a dict pairing keys from test_list_k with values from test_list_v , what you want is zip (which will drop the unpaired key), or itertools.zip_longest (which will allow you to provide a filler value for the unpaired key). The syntax for using it is:

test_dict_comp = {k: v for k, v in zip(test_list_k, test_list_v)}

or for this simple case (where no filtering or transformation is being done, so the comprehension isn't needed), you can just pass the resulting iterator of pairs to the dict constructor directly:

test_dict_comp = dict(zip(test_list_k, test_list_v))

Your code breaks because and is for boolean tests, it can't combine arbitrary statement fragments the way you're attempting. The parser is trying to parse the value to iterate over in the first for loop, and when it gets to test_list_k and for it gets confused (because test_list_k and must be followed by another expression to produce the other value to be tested for truthiness if test_list_k is determined to be truthy, and for is a keyword, not a legal expression for the right hand side of and ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM