Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

python dictionary match key values in two dictionaries

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 to write this code

  aa = {'a': 1, 'c': 3, 'b': 2}
  bb = {'a': 1, 'b': 2}

  for k in aa:
    if k in bb:
      if aa[k] == bb[k]:
         print "Key and value bot matches in aa and bb"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...