1

In PHP you can easily create and populate multidimensional arrays like this:

$points = array();
$points["Landmarks"]["Latitude"] = $some_array_containing_lat_values;
$points["Landmarks"]["Longitude"] = $some_array_containing_lon_values;

What's the pythonic way of doing this?

I already tried lists, dictionaries and numpy arrays, but neither was working. Using unnamed (numbered) arrays is not an option, since they are created from external files with inconsistent structure and naming, so the data must be retrieved from the array by name, not by index.

Sorry if this is a duplicate question, but I've been searching for an entire day to no avail and I'm desperately running out of time.

Mattes
  • 13
  • 3
  • 3
    I don't see why dictionary wouldn't work? Just need to initiate different levels separately: `points = {}`, `points['Landmarks'] = {}`, `points['Landmarks']['Latitude'] = lat_array`, etc. – johmsp Jul 26 '18 at 16:40
  • 3
    Or `points = {'Landmarks': {'Latitude': lat_array}}` – johmsp Jul 26 '18 at 16:41
  • 1
    If you want to skip the `points['Landmarks'] = {}`, you could use a defaultdict -- `points = defaultdict(dict)`,`points['Landmarks']['Latitude'] = lat_array` -- instead – dashiell Jul 26 '18 at 16:56
  • A quick glance at the PHP docs suggests that `array` combines in a sense the functionality of Python `dictionary` and `list`. In Python those are not inherently multidimensional, but either can contain a dictionary or list as values, producing a kind of multidimensionality. You may need to show some of you Python trials and explain what the problem is with each. So far the problem description is too generic. – hpaulj Jul 26 '18 at 17:18

1 Answers1

4

Whenever you want to retrieve an item from a data structure using a string as a keyword (e.g. "Landmarks"), a dictionary is what you're looking for.

To have the "multidimensional" functionality of points["Landmarks"]["Latitude"], you will have to have a dictionary inside another dictionary:

points = {'Landmarks': {'Latitude': lat_array, 'Longitude': lon_array}}

You can also use a deafaultdict, which supports nested dictionaries:

from collections import deafaultdict
points = defaultdict(dict)
points["Landmarks"]["Latitude"] = lat_array
points["Landmarks"]["Longitude"] = lon_array

You can see more about nested dictionaries here.

johmsp
  • 296
  • 1
  • 8