Evaluating values within a dictionary for different keys

萝らか妹 提交于 2019-12-25 03:26:30

问题


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}}


来源:https://stackoverflow.com/questions/25593335/evaluating-values-within-a-dictionary-for-different-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!