Using zip() for dictionary construction

The zip() function is also used for generating dictionaries when the sets of keys and values must be computed at runtime.

Let’s suppose your program obtains dictionary keys and values in lists at runtime.

k = ['honda', 'yamaha', 'suzuki']
v = [3000, 2500, 2000]

print(k, v)

Of course, the terminal will output:

ddn_ro@Linux:~$ python3 test.py
['honda', 'yamaha', 'suzuki'] [3000, 2500, 2000]

If you want these two lists to be a dictionary then zip() the lists and step through them in parallel with a for loop.

k = ['honda', 'yamaha', 'suzuki']
v = [3000, 2500, 2000]

print(k, v)

print(list(zip(k, v)))

D1 = {}
for (a, b) in zip(k, v):
	D1[a] = b

print(D1)

The terminal output will be:

ddn_ro@Linux:~$ python3 test.py
['honda', 'yamaha', 'suzuki'] [3000, 2500, 2000]
[('honda', 3000), ('yamaha', 2500), ('suzuki', 2000)]
{'suzuki': 2000, 'yamaha': 2500, 'honda': 3000}

You can skip the for loop and simply pass the zipped keys/values lists to the built-in dict constructor call (it achieves something like a list-to-dictionary conversion, but it’s really an object construction request).

k = ['honda', 'yamaha', 'suzuki']
v = [3000, 2500, 2000]
D1 = dict(zip(k, v))
print(D1)

The terminal output will be:

ddn_ro@Linux:~$ python3 test.py
{'yamaha': 2500, 'suzuki': 2000, 'honda': 3000}

Leave a Reply