1

Seen a few answers to similar questions, but not built in functions/multiple entry dictionaries. Suppose I have a dictionary containing basemap arguments for different map projections;

Domains = {'TPCentral':["projection='geos',lon_0=-160,lat_0=0,resolution='l'"],
'World':["projection='robin',lon_0=0"]}

I would like to call the basemap function (from maplotlib) such that

m = Basemap(Domains['TPCentral'])

so that this would function equivalently as;

m = Basemap(projection='geos',lon_0=-160,lat_0=0,resolution='l')

Problem is this passes it as one long string, not sure how to break it up into seperate arguments (tried using *). Thanks in advance!

J W
  • 617
  • 1
  • 9
  • 28
  • Have a look at [this question](https://stackoverflow.com/questions/186857/splitting-a-semicolon-separated-string-to-a-dictionary-in-python). – tyteen4a03 May 03 '17 at 16:08
  • I'm not trying to construct a dictionary though. – J W May 03 '17 at 16:11
  • What about this: [question](http://stackoverflow.com/questions/36901/what-does-double-star-and-star-do-for-parameters) – RoaaGharra May 03 '17 at 16:12
  • You can use the dictionary constructed with the answer above and pass it into the function directly with `func(**theDict)` - see [this answer](https://stackoverflow.com/questions/334655/passing-a-dictionary-to-a-function-in-python-as-keyword-parameters). – tyteen4a03 May 03 '17 at 16:13

1 Answers1

1
["projection='geos',lon_0=-160,lat_0=0,resolution='l'"]

is a list containing a single string. Using unpacking on it would result in a list of characters - which would almost surely be a lot larger than the amount of your arguments and surely not the arguments you want to send. You better use a dictionary to keep this values:

'TPCentral': {
    'projection': 'geos',
    'lon_0': -160,
    'lat_0': 0,
    'resolution': 'l'}

and then unpack with a keyword arguments unpacking:

m = Basemap(**Domains['TPCentral'])

If you are forced by this format, you can do a little of string processing, like

pairs = [x.split('=') for x in Domains['TPCentral'][0].split(',')]
Domains['TPCentral'] = {k: eval(v) for k, v in pairs}
Uriel
  • 15,579
  • 6
  • 25
  • 46
  • This is what I was looking for, thank you. I didn't realise dictionaries can contain sublists/dictionaries, i.e. dict = {'x':{'y':{'z':'a=1'}}} – J W May 03 '17 at 16:19
  • Just did - had to wait a couple of mins. – J W May 03 '17 at 16:22