Python equivalent of zip for dictionaries
Dictionary key views are already set-like in Python 3. You can remove set()
:
for key in da.keys() & db.keys():
print(key, da[key], db[key])
In Python 2:
for key in da.viewkeys() & db.viewkeys():
print key, da[key], db[key]
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:
return
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)]
When only one dictionary is provided as an argument, it essentially returns dct.items()
.
>>> list(common_entries(da))
[('c', 3), ('b', 2), ('a', 1)]
With no dictionaries, it returns an empty generator (just like zip()
)
>>> list(common_entries())
[]
The object returned by dict.keys()
(called a dictionary key view) acts like a set
object, so you can just take the intersection of the keys:
da = {'a': 1, 'b': 2, 'c': 3, 'e': 7}
db = {'a': 4, 'b': 5, 'c': 6, 'd': 9}
common_keys = da.keys() & db.keys()
for k in common_keys:
print(k, da[k], db[k])
On Python 2 you'll need to convert the keys to set
s yourself:
common_keys = set(da) & set(db)
for k in common_keys:
print k, da[k], db[k]