Python 相当于 zip 的字典

2022-01-10 00:00:00 python dictionary iterator

问题描述

如果我有这两个列表:

la = [1, 2, 3]
lb = [4, 5, 6]

我可以如下迭代它们:

for i in range(min(len(la), len(lb))):
    print la[i], lb[i]

或者更多的蟒蛇

for a, b in zip(la, lb):
    print a, b

<小时>

如果我有两本字典怎么办?


What if I have two dictionaries?

da = {'a': 1, 'b': 2, 'c': 3}
db = {'a': 4, 'b': 5, 'c': 6}

同样,我可以手动迭代:

Again, I can iterate manually:

for key in set(da.keys()) & set(db.keys()):
    print key, da[key], db[key]

是否有一些内置方法可以让我进行如下迭代?

Is there some builtin method that allows me to iterate as follows?

for key, value_a, value_b in common_entries(da, db):
    print key, value_a, value_b 


解决方案

没有内置函数或方法可以做到这一点.但是,您可以轻松定义自己的.

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)

这建立在手动方法"的基础上.您提供,但像 zip 一样,可用于任意数量的字典.

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)]

当只提供一个字典作为参数时,它本质上返回 dct.items().

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

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

没有字典,它返回一个空的生成器(就像 zip())

With no dictionaries, it returns an empty generator (just like zip())

>>> list(common_entries())
[]

相关文章