简体   繁体   中英

Most efficient way to subtract between two list in every common keys between two python dictionaries

So i have two dictionaries, and for their common keys, i want to find the difference in each elements of the respective lists, the order does not matter in the output.

Here's a small example

x={
    '1' : [1,2,3],
    '2' : [2,9]
}
y={
    '1' : [4,5],
    '3' : [8,9]
}

# Common key is '1' , so z is the list of the subtraction of elements of key '1'
>> expected_output = [-3, -2, -1, -4, -3, -2]
                   = [1-4,2-4,3-4, 1-5,2-5,3-5]

Here is an example of setting up bigger dictionaries with many common keys and uncommon keys

import random

x={}
y={}
num_same_keys = 100
num_diff_keys = 200

## Generating common keys with arbitrary number of elements
common_key = random.randint(0,10000)
for _ in range(num_same_keys) : 
    while common_key in x : common_key = random.randint(0,10000)
    x[common_key] = [ random.randint(0,1000) for _ in range(random.randint(1,10)) ]
    y[common_key] = [ random.randint(0,1000) for _ in range(random.randint(1,10)) ]

## Generating different keys with arbitrary number of elements
x_key = random.randint(0,10000)
y_key = random.randint(0,10000)
for _ in range(num_diff_keys) : 
    # Adding to x    
    while (x_key in x) and (x_key in y) : x_key = random.randint(0,10000)
    x[x_key] = [ random.randint(0,1000) for _ in range(random.randint(1,10)) ]
    # Adding to y
    while (y_key in x) and (y_key in y) : y_key = random.randint(0,10000)
    y[y_key] = [ random.randint(0,1000) for _ in range(random.randint(1,10)) ]

Currently i tried my best to optimise it by calling & on the keys as a set, then extend the list for each of them. However i'm not sure if its the most optimal.

def f1(x,y):
    z = []
    for element in x.keys() & y.keys():
        z.extend([xval-yval for xval in x[element] for yval in y[element] ])
    return z

outputlist = f1(x,y)

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