简体   繁体   中英

How to compare 2 dictionary of tuples to generate this list of dictionary?

I have 2 dictionaries;

Dict1={'John': ('AA', 'BB'), 'Tom': ('XX', 'YY'), 'Jane': ('AA', 'BB')}

Dict2={'John': ('CC', 'DD', '2'), 'Tom': ('CC', 'DD', '1'), 'Jack': ('CC', 'DD', '3')}

Based on these 2 lists, I want to generate a dictionary that looks like this;

OutputDict={'John': ('AA', 'BB', '2'), 'Tom': ('XX', 'YY', '1')}

How it works is this;

  1. Check that the dictionaries inside Dict1 and Dict2 have matching keys.
  2. If they have matching keys, copy the 3rd element of the tuple in Dict2 and paste into the corresponding dictionary in Dict1 to generate OutputDict.

How can this be done in Python? I am using Python2.7.

>>> Dict1={'John': ('AA', 'BB'), 'Tom': ('XX', 'YY'), 'Jane': ('AA', 'BB')}
>>> Dict2={'John': ('CC', 'DD', '2'), 'Tom': ('CC', 'DD', '1'), 'Jack': ('CC', 'DD', '3')}
>>> OutputDict = {}
>>> for k in Dict1:
...     if k in Dict2.keys():
...         OutputDict[k] = tuple(Dict1[k]) + tuple(Dict2[k][2])
... 
>>> OutputDict
{'John': ('AA', 'BB', '2'), 'Tom': ('XX', 'YY', '1')}

There are multiple ways to do what you are trying to do, the easiest one would be the following:

OutputDict = {}
for key in Dict1.iterkeys():
    if key in Dict2:
        OutputDict[key] = Dict1[key] + Dict2[key][2]

Since all the operations are O(1), and we run it for each key on Dict1 (or Dict2 depending) all this runs in O(min(n,m)) where n is the length of Dict1 and m the length of Dict2

A straight-forward solution would look like this, similar to the other answers:

outputDict = {}
for k, v in dict1.items():
    if k in dict2:
        result[k] = v + (dict2[k][2],)

Since this problem is fairly simple, an (arguably) more Pythonic way could make use of dict comprehension instead without compromising readability:

outputDict = {k: v + (dict2[k][2],) for k, v in dict1.items() if k in dict2}

I would also suggest using lower_case or camelCase naming for variables, as per the PEP 8 Style Guide , reserving UpperCase for things like class names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM