python dictionary match key values in two dictionaries

前端 未结 4 608
旧巷少年郎
旧巷少年郎 2020-12-16 04:08

In the below shown dictionaries i want to check whether the key in aa matches the key in bb and also the value corresponding to it matches in bb or not.Is there a better way

相关标签:
4条回答
  • 2020-12-16 04:35

    This can be written as one-liner with all:

    all(bb[k] == v for k, v in aa.iteritems() if k in bb)
    

    It's also more declarative approach, which might convey the intent better.

    0 讨论(0)
  • 2020-12-16 04:53

    If you want to iterate over all matching key/value pairs, you can use

    for key, value in aa.viewitems() & bb.viewitems():
        ...
    

    (Python 2.7)

    0 讨论(0)
  • 2020-12-16 04:57

    Use sets to find all equivalents:

    for (key, value) in set(aa.items()) & set(bb.items()):
        print '%s: %s is present in both aa and bb' % (key, value)
    

    The & operator here gives you the intersection of both sets; alternatively you could write:

    set(aa.items()).intersection(set(bb.items()))
    

    Note that this does create full copies of both dicts so if these are very large you this may not be the best approach.

    A shortcut would be to only test the keys:

    for key in set(aa) & set(bb):
        if aa[key] == bb[key]:
            print '%s: %s is present in both aa and bb' % (key, value)
    

    Here you only copy the keys of each dict to reduce the memory footprint.

    When using Python 2.7, the dict type includes additional methods to create the required sets directly:

    for (key, value) in aa.viewitems() & bb.viewitems():
        print '%s: %s is present in both aa and bb' % (key, value)
    

    These are technically dictionary views but for the purposes of this problem they act the same.

    0 讨论(0)
  • 2020-12-16 04:57
    aa = {'a': 1, 'c': 3, 'b': 2}
    bb = {'a': 1, 'b': 2}
    
    [k for k,v in aa.items() if k in bb]
    
    ['a', 'b']
    

    Python 3

    0 讨论(0)
提交回复
热议问题