Shmink Shmink - 23 days ago 4x
Python Question

Ignore or sidestep a name error

I feel like I'm turning a molehill into a mountain here but I can't think of or don't know of a better way to do this.

In short, I have a list of lists that looks like:

[ [4.54323, 5.4325], [7.235, 3.67543], [9.342543, 1.65323] ]

And I need a list that looks like the following:

[ {lat: 4.54323, lng: 5.4325}, {lat: 7.235, lng: 3.67543}, {lat: 9.342543, lng: 1.65323} ]

I've done some things I'm not proud of and have ended up with:

[ '{lat: 4.54323, lng: 5.4325}', '{lat: 7.235, lng: 3.67543}', '{lat: 9.342543, lng: 1.65323}' ]

Yup, some string manipulation and now I'm stuck with a list of strings. I then tried to evaluate each element in said list but got a
NameError: name 'lat' is not defined.

So this more of a multi-part question. Is there a way to get what I want without turning elements into strings and replacing characters? Or alternatively, can I evaluate or turn these strings into whatever data type they should be (I think sets). This variable is only going to be sent to a HTML file to replace a variable by using Jinja. So it doesn't really need to be understood by python, (I'm using 2.7.x).

EDIT: This is the method I'm working with, I'm actively trying not to share that much code because of work reasons, sorry. There's also a lot of different attempts been made in the lifetime of the method. So some lines may look weird.

evalledCoords = []

def make_points(coords):
for x in range(0, len(coords)):
# remove first element, not needed.
coords[x] = str(coords[x]).replace("[", "{lat: ").replace(",", ", lng:").replace("]", "}")
# See outputs
print '\n', coords[x]
print 'evalled coords', evalledCoords.append(eval(coords[x]))
return coords


Based on the provided data structures and what expected output you are looking to achieve, this can be done through a simple loop over your existing data structure and creating a new list of dictionaries:

coords = [ [4.54323, 5.4325], [7.235, 3.67543], [9.342543, 1.65323] ]

new_list = []
for data in coords:
        'lat': data[0],
        'lng': data[1]

# [{'lng': 5.4325, 'lat': 4.54323}, {'lng': 3.67543, 'lat': 7.235}, {'lng': 1.65323, 'lat': 9.342543}]

Or, simply as a list comprehension:

new_list = [{'lat': d[0], 'lng': d[1]} for d in coords]

# [{'lng': 5.4325, 'lat': 4.54323}, {'lng': 3.67543, 'lat': 7.235}, {'lng': 1.65323, 'lat': 9.342543}]