Python equivalent of zip for dictionaries

前端 未结 5 1366
迷失自我
迷失自我 2020-12-13 18:10

If I have these two lists:

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

I can iterate over them as follows:

for i in range(min(len(la), le         


        
5条回答
  •  情深已故
    2020-12-13 18:22

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

提交回复
热议问题