Home > other >  Python search and compare Dict-values (coordinates-list) to a list (bbox) and return specific key
Python search and compare Dict-values (coordinates-list) to a list (bbox) and return specific key

Time:10-23

I have a dict with values like this (coordinates = [cx1, cx2, cy1, cy2]):

> co_list =
[
  {
    "data.01": [
      6.9490666,
      47.4897206,
      7.0073678,
      47.5169333
    ]
  },
  {
    "data.02": [
      6.9493157,
      47.4627392,
      7.0075872,
      47.4899521
    ]
  }
]

from an user input I got a list with 4 coordinates (bbox = [bx1, by1, bx2, by2])

bb_list = [6.974532, 47.469739, 7.000004, 47.481432]

I want to check if the bb_list fits in the co_list's values, if the bottom left or the upper rigth corner is within a certain range, the according key shall be returned. How can I iterate the values of bb_list over each value/values of co_list and they should be compared by something like that:

if bx1 >= cx1 and <= cx2 and if by1 >= cy1 and <= cy2 or if bx2 >= cx1 and <= cx2 and if by2 <= cy2 and >= cy1

Any help welcome, thanks!

CodePudding user response:

How about this.

code

co_list = [
  {
    "data.01": [
      6.9490666,
      47.4897206,
      7.0073678,
      47.5169333
    ]
  },
  {
    "data.02": [
      6.9493157,
      47.4627392,
      7.0075872,
      47.4899521
    ]
  }
]

bb_list = [6.974532, 47.469739, 7.000004, 47.481432]

# Loop thru the list
for c in co_list:
    # Loop thru dict
    for k, v in c.items():
        cx1 = v[0]
        cx2 = v[1]
        cy1 = v[2]
        cy2 = v[3]

        # take the element of a list
        bx1 = bb_list[0]
        by1 = bb_list[1]
        bx2 = bb_list[2]
        by2 = bb_list[3]

        if (bx1 >= cx1 and bx1 <= cx2 and by1 >= cy1 and by1 <= cy2 
            or bx2 >= cx1 and bx2 <= cx2 and by2 <= cy2 and by2 >= cy1):
            print(k)

output

data.01
data.02
  • Related