BioInformatician
BioInformatician

Reputation: 97

Comparing Multiple Dictionaries With Specific Values

I have four dictionaries of similar length.

I want to:

  1. get those keys that are matched between the four.

  2. Iterate over certain value in each dictionary which I will compare later and do some arithmetic operations.

I have done that using nested loop (four loops) but that doesn't look efficient at all. I want to make this code more efficient and elegant.

I want to do that without doing nested loop:

 d1 = {1:18:[['28','Y','N'],['108','A','M'],...]
 d2,d3 and d4 are the same thing expect different values but some will have same keys 
 for k, v in di1.iteritems():
    for v1 in v:
          for k2,v2 in di2.iteritems():
                      for va2 in v2:
                            if k == k2:
                             for k3,v3 in di3.iteritems():
                              for va3 in v3:
                                if k2 == k3:
                                 for k4,v4 in di4.iteritems():
                                   for va4 in v4:
                                    if k3==k4 and k==k4 and k==k3:
                                      # do some arithmetics on dictionary's values for all four dictionaries

Thanks a lot in advance.

Upvotes: 0

Views: 4670

Answers (2)

THK
THK

Reputation: 701

1) I assume "get those keys that are matched between the four" means you want to find keys that are present in ALL four dictionaries. One way to achieve this is to take the intersection of the four sets of keys.

common_keys = set(d1.keys()) & set(d2.keys()) & set(d3.keys()) & set(d4.keys())

2) Iterate over the common keys and "do some arithmetics on dictionary's values for all four dictionaries":

for key in common_keys: 
    for dict in [d1, d2, d3, d4]:
        # do something with dict[key]...

You can also use list comprehensions if you wish to avoid nested loops, e.g. generate a list of (key, list of tuples) pairs and operate on that later:

common_keys_vals = [(key, [dict[key] for dict in [d1, d2, d3, d4]])
                    for key in common_keys]

Upvotes: 0

fferri
fferri

Reputation: 18950

if they have the same keys, then di1.keys() == di2.keys() == di3.keys() == di4.keys().

keys = di1.keys()
for k in keys:
    # do something with di1[k] di2[k] di3[k] di4[k]

if they do not all have the keys, build the union set of the keys, and check which dict has each key, using in:

keys = set(di1.keys()) | set(di2.keys()) | set(di3.keys()) | set(di4.keys())
for k in keys:
    if k in di1:
        # di1 has the key
    if k in di2:
        # di2 has the key
    if k in di1 and k in di2:
        # do something with di1[k] and di2[k]
    # ...

Upvotes: 2

Related Questions