PYTHON
Creating a Dictionary from Two Lists
Learn to efficiently construct a Python dictionary by pairing elements from two separate lists (one for keys, one for values) using `zip()` and `dict()`, useful for data transformation in web projects.
field_names = ["username", "email", "password_hash", "last_login"]
user_values = ["john_doe", "[email protected]", "sha256abc123", "2023-10-27T10:30:00Z"]
# Create a dictionary using zip and dict constructor
user_profile_data = dict(zip(field_names, user_values))
# Example with different length lists (zip stops at the shortest)
short_keys = ["id", "name"]
long_values = [101, "Alice Smith", "active"]
partial_dict = dict(zip(short_keys, long_values))
# More robust approach for potentially missing values, providing defaults
form_keys = ["name", "age", "city"]
form_data_values = ["Bob", 28] # 'city' is missing
combined_data = {}
# Extend values list with None if shorter than keys, then iterate and apply default
processed_values = (form_data_values + [None] * max(0, len(form_keys) - len(form_data_values)))[:len(form_keys)]
for key, value in zip(form_keys, processed_values):
combined_data[key] = value if value is not None else "N/A"
# print(f"User profile data: {user_profile_data}")
# print(f"Partial dictionary: {partial_dict}")
# print(f"Combined data with defaults: {combined_data}")
How it works: This snippet demonstrates a concise and Pythonic way to create a dictionary from two lists: one containing keys and the other containing corresponding values. The `zip()` function pairs elements from the lists, and the `dict()` constructor then converts these key-value pairs into a dictionary. This is particularly useful when processing tabular data, converting form submissions, or aligning structured data from different sources in your web application backend. It also shows how to handle scenarios where input lists might have different lengths, ensuring robust dictionary creation with default values for missing entries.