Skip to content

Python zip dictionary

  • by

You can zip dictionary same as do zip list using zip() function in Python. The function takes in iterables as arguments and returns an iterator.

Python zip dictionary

Simple example code. Dictionary comprehension is an elegant and concise way to create dictionaries.

dictionary = {key: value for vars in iterable}
stocks = ['IBM', 'Apple', 'Netflix']
prices = [175, 127, 50]

res = {stocks: prices for stocks,
 prices in zip(stocks, prices)}


Python zip dictionary

There is no built-in function or method that can do this. However, you could easily define your own.

def common_entries(*dcts):
    if not dcts:
    for i in set(dcts[0]).intersection(*dcts[1:]):
        yield (i,) + tuple(d[i] for d in dcts)

This builds on the “manual method” you provide, but, like zip, can be used for any number of dictionaries.

>>> da = {'a': 1, 'b': 2, 'c': 3}
>>> db = {'a': 4, 'b': 5, 'c': 6}
>>> list(common_entries(da, db))
[('c', 3, 6), ('b', 2, 5), ('a', 1, 4)]

Do comment if you have any doubts or suggestions on this Python zip topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *