In Python, when you have separate lists for keys and values, the most standard and elegant way to combine them into a single dictionary is to use the zip() function.
There is no need to write a for loop to add items one by one. You can implement this conversion concisely using only built-in functions.
Implementation Example: Mapping Currency Codes to Symbols
In this scenario, we create a lookup dictionary from a list of currency codes (USD, JPY, etc.) and a corresponding list of currency symbols ($, ¥, etc.).
Source Code
# List of keys (Currency Codes)
currency_codes = ["USD", "EUR", "JPY", "GBP"]
# List of values (Currency Symbols)
currency_symbols = ["$", "€", "¥", "£"]
# 1. Use zip() to combine the two lists into an iterator of tuples (pairs)
# 2. Pass it to the dict() constructor to create a dictionary
currency_map = dict(zip(currency_codes, currency_symbols))
# Output results
print("--- Currency Mapping Dictionary ---")
print(currency_map)
# Example of accessing the dictionary
target_code = "JPY"
if target_code in currency_map:
print(f"\nThe symbol for {target_code} is {currency_map[target_code]}.")
Execution Result
--- Currency Mapping Dictionary ---
{'USD': '$', 'EUR': '€', 'JPY': '¥', 'GBP': '£'}
The symbol for JPY is ¥.
Explanation
The Role of the zip Function
zip(list_a, list_b) takes elements from the same index in each list and returns an iterator that generates tuple pairs: (a[0], b[0]), (a[1], b[1]), ....
Integration with the dict Constructor
The dict() constructor accepts an iterable containing tuples in the format (key, value) and automatically converts it into a dictionary. Combining these two creates the common idiom: dict(zip(keys, values)).
Note: When List Lengths Differ
If the two lists have different lengths (number of elements), zip() stops at the end of the shorter list. The remaining elements are ignored. To prevent data loss, check the list lengths beforehand or consider using itertools.zip_longest.
