简体   繁体   中英

Referencing nested dictionary keys and values in dict comprehensions

I asked this question earlier today: Evaluating values within a dictionary for different keys

The structure of the dictionary I'm working with has changed and I've attempted to modify the solution I was given to accommodate this.

The structure before was:

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

but now it has been changed to:

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

I'm attempting to apply a haversine formula on the locsOne dictionary, get the key:value's distance to the other key:values and if they are greater than 450, they should not be included in the results dictionary.

The resulting dictionary should look like this:

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

This is the code which I received (thanks to falsetru):

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)

My attempts at modifying it return errors such as "IndexError: list out of range" and "KeyError".

My last modification is:

for k1 in locsOne:
        v1 = locsOne[k1][1]
        locsTwo[k1] = {k2: harvesineForm(v1 , locsOne[k2][1]) for k2 in locsOne
                   if k1 != k2 and abs(v1 - locsOne[k2][0]) <= 450}

Any help would be greatly appreciated.

a = [[100]]
print a       # [[100]]
print a[0]    # [100]
print a[0][0] # 100

Following the assumption that the values always contain a single value in a list, nested in a list:

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

for k1 in locsOne:
    v1 = locsOne[k1][0][0]
    locsTwo[k1] = {k2: abs(v1 - locsOne[k2][0][0]) for k2 in locsOne
                   if k1 != k2 and abs(v1 - locsOne[k2][0][0]) <= 450}
print(locsTwo)

You simply have to access the first value ( [0] ) of the list again, since you have one more level of lists.

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