MorayM
MorayM

Reputation: 2687

Find an item in a list of lists by multiple elements

I'm using a web API to get some geographical information, which returns data in the following format:

[
    [lat, lon, another_value, more_values...],
    [lat, lon, another_value, more_values...],
    ...
]

The first two values in each sublist (the lat and lon values) can together be considered a unique identifier. I'm making multiple calls to this API to update my data and would like to be able to replace any lat/lon pairs that already exist with the new values.

My initial thought is to sort the list of lists by both the lat and lon values and then do a binary search, but while there are plenty of example of how to sort by a single sublist element, I can't work out how to sort by multiple list elements. Of course, if anyone has a better way of identifying a sublist by the first two elements, that would be greatly appreciated too!

Upvotes: 2

Views: 156

Answers (2)

pzp
pzp

Reputation: 6597

@Yasser Elsayed's answer is pretty good, but if you'd still like to sort the data by latitude then longitude, you should use operator.itemgetter().

import operator as op

data = [[0.0, 24.6, 13],
        [1.0, 53.3, 8],
        [1.0, 51.1, 12],
        [-1.7, 37.4, 26]] # arbitrary sample data

data = sorted(data, key=op.itemgetter(0, 1))

print data
# [[-1.7, 37.4, 26], [0.0, 24.6, 13], [1.0, 51.1, 12], [1.0, 53.3, 8]]

Upvotes: 1

yelsayed
yelsayed

Reputation: 5532

You can use a dictionary to store and query the data as you get it from the API. This way you can just use a tuple (lat, lon) as the key.

d = {}
for line in result:
    d[line[0], line[1]] = line[2:]

This takes care of both storing and querying in one shot, as long as the data format is fixed.

Upvotes: 3

Related Questions