Home > Net >  find a set of values in a python dictionary based on its name
find a set of values in a python dictionary based on its name

Time:09-25

My JSON file has the following structure:

{ 
  "sets": 
          [ { "Name": "set1",  "Values": [ "value11", "value12" ] },
            { "Name": "set2",  "Values": [ "value21", "value22" ] } 
          ] 
}

The names are more meaningful than that, and there is more in the JSON. It is read by the json package into a dictionary, and my python script at some point needs the values from either set1 or set2.

There are more than 2 sets in reality, and to find the right set to use, I now use this for-loop:

for s in protocol_data [ "sets" ]:
    if ( s [ "Name" ] == "set2" ):
       # do stuff with "Values"

So every time another set is needed, the whole array of sets needs to be traversed, which somehow does not feel like it's the way dict was intended. Could there be a cleverer way (maybe with a different container than dict)?

CodePudding user response:

How about preparing the data once. This trades off memory for runtime if you access the data multiple times.

protocol_data_sets = {s['Name']: s['Values'] for s in protocol_data['sets']}

Then you can access all sets via protocol_data_sets['the set you need']

  • Related