Evaluating values within a dictionary for differen

2019-09-17 04:23发布

问题:

I have a nested dictionary to which I would like to obtain the differences between each value.

locsOne = {1:[100], 2:[200], 3:[250]}

(these values here are just examples) I'm attempting to apply a abs(-) function to each key:value to get the distance between each and create a dictionary with the results. How I'd like the results to be formatted would be:

locsTwo = {1:{2:100, 3:150}, 2:{1:100, 3:50}, 3:{1:150, 2: 50 }}

My current attempt is:

for i in range(len(listOne)):
    if abs(listOne[i] - listTwo[i]) >= 450:
        pass
    else:
        distances.append(abs(listOne[i] - listTwo[i]))

Kind of at a loss on how to do this. Any help would be appreciated.

EDIT:

I'm checking if the difference is greater that 450 in the loop so that any values that differ greater than 450 are discarded / not included in our result set.

回答1:

locsOne = {1:[100], 2:[200], 3:[250]}
locsTwo = {}
for k1 in locsOne:
    v1 = locsOne[k1][0]
    locsTwo[k1] = {k2: abs(v1 - locsOne[k2][0]) for k2 in locsOne
                   if k1 != k2 and abs(v1 - locsOne[k2][0]) <= 450}
print(locsTwo)

output:

{1: {2: 100, 3: 150}, 2: {1: 100, 3: 50}, 3: {1: 150, 2: 50}}