How can I make a dictionary (dict) from separate lists of keys and values?
Let's quickly zip
our way to victory:
Generates:
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:
When values outnumber keys, excess values are quietly dropped without a fuss:
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:
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:
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()
!
Morphing your existing dictionary
Got an existing dictionary and new data flying in? Save the day with dictionary's super-method update()
:
Was this article helpful?