Home > Mobile >  Compare two dict and update one of them
Compare two dict and update one of them

Time:07-28

I have two dictionaries like the following:

dict1 = 
{'a': [67.0, 24.0, 45.0, 45.0, 45.0, 23.0, 21.0, 45.0],
 'b': [0.9, 0.5, 9.0, 4.5, 54.0, 0.0, 0.0, 0.0],
 'c': [1.0, 5.0, 40.0, 30.0, 20.0, 0.0, 10.0, 50.0],
 'd': [60.0, 80.0, 56.0, 34.0, 78.0, 13.0, 0.0, 70.0]}

dict2 = 
{'a': 0.897,'c': 3.4, 'd': 34.567}

I want all the values in dict1 to be shifted right by value of 1. The keys of dict1 and dict2 are compared. If there exist a value for the similar keys indict2, the value is put as the first element in the values of dict1 (which is a list). If there exist no value in dict2, the value the first element is 0.0. For eg:

When the two dictionaries are compared, dict2 contains values for the key 'a', 'c', 'd'. So the values for these keys are put as the first element in the value of dict1 (which is a list) while shifting the other elements of the list to right. The size of the list is maintained. For the keys which do not contain a value in dict2, a value of 0.0 is put as the first element in the list as shown below

dict1 = 
{'a': [0.897, 67.0, 24.0, 45.0, 45.0, 45.0, 23.0, 21.0],
 'b': [0.0, 0.9, 0.5, 9.0, 4.5, 54.0, 0.0, 0.0, 0.0],
 'c': [3.4, 1.0, 5.0, 40.0, 30.0, 20.0, 0.0, 10.0],
 'd': [34.567, 60.0, 80.0, 56.0, 34.0, 78.0, 13.0, 0.0]}

CodePudding user response:

You can iterate over dict1 and if the key exists in dict2, insert the value from dict2 into the index 0 of list in dict1 or insert zero with the default value with dict.get.

for k,v in dict1.items():
    dict1[k].insert(0, dict2.get(k,0))
      
print(dict1)

{
    'a': [0.897, 67.0, 24.0, 45.0, 45.0, 45.0, 23.0, 21.0, 45.0], 
    'b': [0, 0.9, 0.5, 9.0, 4.5, 54.0, 0.0, 0.0, 0.0], 
    'c': [3.4, 1.0, 5.0, 40.0, 30.0, 20.0, 0.0, 10.0, 50.0], 
    'd': [34.567, 60.0, 80.0, 56.0, 34.0, 78.0, 13.0, 0.0, 70.0]
}

CodePudding user response:

If this operation is done repeatedly I suggest you use a deque, the time complexity of appending to the left of deque is O(1) (in a list is O(n)).

from collections import deque

dict1 = {k: deque(v, maxlen=len(v)) for k, v in dict1.items()}

for key, value in dict1.items():
    value.appendleft(dict2.get(key, 0.0))


print(dict1)

Output

{'a': deque([0.897, 67.0, 24.0, 45.0, 45.0, 45.0, 23.0, 21.0], maxlen=8),
 'b': deque([0.0, 0.9, 0.5, 9.0, 4.5, 54.0, 0.0, 0.0], maxlen=8),
 'c': deque([3.4, 1.0, 5.0, 40.0, 30.0, 20.0, 0.0, 10.0], maxlen=8),
 'd': deque([34.567, 60.0, 80.0, 56.0, 34.0, 78.0, 13.0, 0.0], maxlen=8)}
  • Related