Explain Codes LogoExplain Codes Logo

How can I make a dictionary (dict) from separate lists of keys and values?

python
zip-dict
memory-management
code-readability
Alex KataevbyAlex Kataev·Aug 17, 2024
TLDR

Let's quickly zip our way to victory:

# Wrap your key-value pairs in a nice, warm dictionary my_dict = {k: v for k, v in zip(['bravo6', 'roger9'], ['going_dark', 'loud_n_clear'])}

Generates:

{'bravo6': 'going_dark', 'roger9': 'loud_n_clear'}

Breaking down the zip-dict technique

Python's zip() function pairs items from two or more lists, tubes, or tuples and creates a zip object. Wrap this in a dict() and voila! — you get a dictionary. It's like having a personal butler neatly pairing your socks for you.

Special cases and slaying anomalies

While the basic solution is straightforward, let's look at different scenarios and fine-tuning that can make your code more robust and efficient.

The unequal lists situation

Python's zip() function is very considerate. It stops pairing when one of the lists runs out of elements.

Here's a demonstration when we have more keys than values:

keys = ['coffee', 'cream', 'sugar', 'stirrer'] values = [1, 2, 3] my_dict = dict(zip(keys, values)) # Result: {'coffee': 1, 'cream': 2, 'sugar': 3} # Stirrer remains lonely :(

When values outnumber keys, excess values are quietly dropped without a fuss:

keys = ['coffee', 'cream', 'sugar'] values = [1, 2, 3, 4] my_dict = dict(zip(keys, values)) # Result: {'coffee': 1, 'cream': 2, 'sugar': 3} # The extra scoop of sugar got zapped!

Memory management in Python 2

Python 2's zip() function generates a list, which can gulp down your memory for large lists 🦖. In Python2 use itertools.izip for a memory-friendly operation:

from itertools import izip my_dict = dict(izip(long_keys_list, long_values_list)) # izip is Python 2's memory-friendly buddy!

Time trials: Benchmarking performance

For large data, dict(zip()) tend to be quicker than manual loops or even comprehensions. 👨‍🎤 "I want it all, and I want it now" 👨‍🎤

Evaluate your code's execution speed using the timeit.repeat() function:

import timeit fastest_time = min(timeit.repeat(lambda: dict(zip(keys, values)))) # Now you're cooking with gas!

Code readability: Keeping things clean and readable

Besides being a Dakota Fanning of efficiency, dict(zip()) is also a Benedict Cumberbatch of cleanliness. Its syntax is an eye-candy — easy to read, easy to understand. Why write a novella when a haiku will do the job?

Dictionary creation in real-life challenges

zip() is not just for static lists. You can mingle dynamic data, coming right from the thrill of live databases or APIs. Let the good times zip()!

# Captain... we're receiving data transmission! user_ids = get_user_ids_from_database() emails = get_user_emails_from_api() # Make it so! users_dict = dict(zip(user_ids, emails))

Morphing your existing dictionary

Got an existing dictionary and new data flying in? Save the day with dictionary's super-method update():

# Hold on, cap, we've got new arrivals! existing_dict.update(dict(zip(new_keys, new_values))) # And... we're done. Phew!