If the keys from the two dictionaries are equal, perform the operation using both values ​​and go to the new dict (python)

I have two dictionaries, for example:

d1 = {'red':10, 'blue':20, 'green':30, 'yellow':40}
d2 = {'red':1, 'blue':2, 'green':3}

I want to go through each element in d1 and see if the key matches the key in d2. If so, I want to subtract d2 from d1 and move the new key / value pair to a new dictionary, with the result:

d3 = {'red':9, 'blue':18, 'green':27, 'yellow':40}

I wrote the following for this script:

for x, y in d1.items():
    for a, b in d2.items():
        if x == a:
            d3[x] = (y-b)
        elif x not in d2.items():
            d3[x] = y

This works, but when I try to use it on two dictionaries with thousands of elements, the function never ends. I think this is too slow.

Can you recommend a better way to do this? Many thanks.

+4
source share
3 answers

, , :

{k:v1-d2.get(k,0) for k,v1 in d1.items()}

:

>>> {k:v1-d2.get(k,0) for k,v1 in d1.items()}
{'red': 9, 'blue': 18, 'green': 27, 'yellow': 40}

: items() d1, k v1 d1, k.

- v1-d2.get(k,0) k . d2.get(k,0) , k, , 0.

- O (1) ( , ) - O (n) n d1, .

+7

dict if-else:

d1 = {'red':10, 'blue':20, 'green':30, 'yellow':40}
d2 = {'red':1, 'blue':2, 'green':3}

new_dict = {a:b-d2[a] if a in d2 else b for a, b in d1.items()}

:

{'blue': 18, 'green': 27, 'red': 9, 'yellow': 40}
+3

( ) collections.Counter ( ) :

In [1]: from collections import Counter

In [2]: d1 = {'red':10, 'blue':20, 'green':30, 'yellow':40}
   ...: d2 = {'red':1, 'blue':2, 'green':3}
   ...: 

In [3]: A = Counter(d1)

In [4]: B = Counter(d2)

In [5]: A - B
Out[5]: Counter({'blue': 18, 'green': 27, 'red': 9, 'yellow': 40})

@WillemVanOnsem,

", d2 , d1, , : , ".

, Counter, substract() ( python 3.2), Counter ( dict.update():

In [26]: A = Counter({'red':10, 'blue':20, 'green':30, 'yellow':40})
    ...: B = Counter({'red':1, 'blue':30, 'green':3})
    ...: 

In [27]: A - B # The 'blue' key disappear 
Out[27]: Counter({'green': 27, 'red': 9, 'yellow': 40})

In [28]: A.subtract(B) # It handles negative values ...

In [29]: A # ...but modify the counter A
Out[29]: Counter({'blue': -10, 'green': 27, 'red': 9, 'yellow': 40})

The main goal collections.Counteris, in particular, counting / saving the occurrences of hashed objects (thus, accepting values ​​that are natural numbers), but basically it is a subclass of dict that provide several operations for combining objects Counterbetween them (addition, subtraction, union and intersection )

+2
source

Source: https://habr.com/ru/post/1679676/


All Articles