Convert Two Lists to a Dictionary in Python (zip)
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
This snippet demonstrates a clean, one-line way to turn two separate lists — one of keys and one of values — into a single Python dictionary.
How the code works:
- Two example lists are defined:
keys_list = ['a', 'b', 'c']andvalues_list = [1, 2, 3]. zip(keys_list, values_list)pairs each key with the value at the same index, producing tuples like('a', 1).dict()consumes those pairs and builds the dictionary.- The result is printed:
{'a': 1, 'b': 2, 'c': 3}.
Important notes:
- If the lists have different lengths,
zip()stops at the shortest one and the extra elements are silently dropped. - If a key appears more than once, the last value wins.
- An equivalent alternative is a dict comprehension:
{k: v for k, v in zip(keys_list, values_list)}
Common use cases: building a mapping from two CSV columns, converting two database query result columns into a lookup table, or mapping IDs to names.