0

I'm attempting to iterate through a list of dictionaries and extract values based on the key and the dictionary index.

My goal is to assign the values from my first dictionary to the variables x1/y1, then move on and do the same with my second dictionary to variables (x2, y2), I will then perform a calculation. Once the calculation has been performed, I'd like to do the same with dictionary 2/3 and so on until I have calculated all of the dictionaries in the list.

I'm stuck because I cannot reference the dictionary index. Currently my code only stores values in lon1/lat1.

lst = [{'lat': 1, 'Time': 1, 'lon': 1},
       {'lat': 2, 'Time': 2, 'lon': 2},
       {'lat': 3, 'Time': 3, 'lon': 3}]

x1 = () 
x2 = ()
y1 = ()
y2 = ()

for k, v in [(k, v) for x in lst for (k, v) in x.items()]:
   if k == 'lon'
       x1 = v
   elif k == 'lat':
       y1 = v
   elif k == 'lat':
       x2 = v
   elif k == 'lon':
        y2 = v

Edit: Removed unnecessary code and attempted explain my goal more concisely. I elected to keep the unnecessary variables because I’m required to use a canned formula with those variables for the calculation.

C. Brookes
  • 31
  • 5
  • Why do you want to do this? It seems rather inefficient. – gmds Mar 01 '19 at 00:28
  • Please rewrite this with a simple problem. Having four nested loops to carry out a single iteration operation *really* hides the overall purpose of this. Also, using custom-named variables instead of an iterable (such as a list) for `lon` and `lat` makes this even harder to follow. – Prune Mar 01 '19 at 00:42
  • Prune - Thank you for the feedback. I edit my post and keep this in mind moving forward. – C. Brookes Mar 01 '19 at 00:51
  • Marcus Lim - You’re right, the code I posted is extremely inneficeint. I wasn’t looping in that manner for any particular reason, I was just in over my head. I was attempting to iterate through the dictionaries and store the values anyway I could. – C. Brookes Mar 01 '19 at 01:12

2 Answers2

0

Dicts are meant to be accessed by keys (so to take advantage of the O(1) time complexity in value retrieval), rather than being iterated over in search of a key. For your purpose of processing the list items in rolling pairs you can zip the list with itself with an offset of 1 for iteration instead:

for a, b in zip(lst, lst[1:]):
    lon1 = a['lon']
    lat1 = a['lat']
    lon2 = b['lon']
    lat2 = b['lat']
    # perform your calculations for the pair of dict a and dict b
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • 1
    This is exactly what I wanted to do. Thank you. I should have read this thread about slicers before going into an endless for loop and asking this question. https://stackoverflow.com/questions/509211/understanding-slice-notation – C. Brookes Mar 01 '19 at 02:54
0

Perhaps this will help your organization? The print statements are merely to illustrate that you've extracted the coordinates properly.

lon_lat = []
for point in lst:
    lon_lat.append( (lst["lon], lst["lat]) )

print (lon_lat[0])
print (lon_lat[1])

Output:

(1, 1)
(2, 2)

lon_lat is a list of tuples holding the lon and lat of each position. You can just as easily use these for a calculation.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • Thank you for this example. I will generally be storing data in this manner so this answer is also very useful. – C. Brookes Mar 01 '19 at 02:58