dictionary - How to add the values of two OrderedDict objects in python, keeping the order? -


i add 2 ordereddict objects these:

dict1 = ordereddict([('table', [10, 20, 30, 'wood']), ('chair', [200, 300, 400, 'wood'])]) dict2 = ordereddict([('table', ['red', 55]), ('chair', ['blue', 200])]) 

and create new ordereddict (the order important):

dict3 = ordereddict([('table', [10, 20, 30, 'wood', 'red', 55]), ('chair', [200, 300, 400, 'wood', 'blue', 200])]) 

if there keys in dict1 or dict2 not present in other, should ignored, matching keys should used output. values lists.

because want preserve order of ordereddict objects, need loop on 1 , test each key against other produce union of 2 key sets:

dict3 = ordereddict((k, dict1[k] + dict2[k]) k in dict1 if k in dict2) 

looping on dict1 ensures output keys new dictionary in same order, testing k in dict2 ensures use keys present in both input mappings.

you can update dict1 in-place list.extend():

for key, value in dict1.items():     if key in dict2:         value.extend(dict2[key]) 

demo:

>>> collections import ordereddict >>> dict1 = ordereddict([('table', [10, 20, 30, 'wood']), ('chair', [200, 300, 400, 'wood'])]) >>> dict2 = ordereddict([('table', ['red', 55]), ('chair', ['blue', 200])]) >>> ordereddict((k, dict1[k] + dict2[k]) k in dict1 if k in dict2) ordereddict([('table', [10, 20, 30, 'wood', 'red', 55]), ('chair', [200, 300, 400, 'wood', 'blue', 200])]) 

Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -