I want to combine these: keys = ['name', 'age', 'food'] values = ['Monty', 42, 'spam'] Into a single dictionary: {'name': 'Monty', 'age': 42, 'food': 'spam'}
You can combine the keys
and values
lists into a single dictionary in Python using the zip()
function along with a dictionary comprehension. Here's how you can do it:
python
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
result_dict = {k: v for k, v in zip(keys, values)}
print(result_dict) # Output: {'name': 'Monty', 'age': 42, 'food': 'spam'}
In this example, zip(keys, values)
pairs up the corresponding elements from the keys
and values
lists, and the dictionary comprehension {k: v for k, v in ...}
constructs a dictionary using those pairs. The result is the desired dictionary {'name': 'Monty', 'age': 42, 'food': 'spam'}
.
Comments
Post a Comment