且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python相当于zip的字典

更新时间:2022-10-15 20:48:17

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

def common_entries(*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)]

When only one dictionary is provided as an argument, it essentially returns dct.items().

>>> list(common_entries(da))
[('c', 3), ('b', 2), ('a', 1)]

相关阅读

技术问答最新文章