Home > Mobile >  Looking up a value in a nested dictionary to get a value in a separate dictionary but same parent di
Looking up a value in a nested dictionary to get a value in a separate dictionary but same parent di

Time:06-16

In the response that comes back from an API request. I get a format that is a list of nested dictionaries. for example.

{
  "data": [
    {
      "3": {
        "value": 1
      },
      "6": {
        "value": "Conversion"
      },
      "7": {
        "value": "HVAC"
      }
    },

I can easily get past the the first dictionary using r['data']. At this point, each list item is a record in a database. r['data'][0] gives me a dictionary of what the field ('3') is and then a dictionary of what the value is ({'value': 'Conversion'}).

I want to be able to look up a value like 'Conversion' and have it tell me what the value is for field '3'. Anyway to do this using python?

CodePudding user response:

Your description doesn't quite fit with reality. Let's have a complete structure:

r = {
    "data": [
        {
            "3": {
                "value": 1
            },
            "6": {
                "value": "Conversion"
            },
            "7": {
                "value": "HVAC"
            }
        }
    ]
}

r is a dictionary. It contains a single key ('data') whose associated value is a list which, in this example, contains one dictionary. That dictionary has 3 keys - "3", "6" and "7". Each of those keys has a value which itself is a dictionary comprised of a single key ('value') and, obviously, an associated value.

You can assert as follows:

assert r['data'][0]['6']['value'] == 'Conversion'

Hopefully that shows how you can access the lower level value(s)

What's unclear from your question is why would you be searching for 'Conversion' when you want the value from key '3' which would be:

r['data'][0]['3']['value']

EDIT:

def get_value(r, from_key, ref_key, value):
    for d in r['data']:
        if d.get(from_key, {}).get('value') == value:
            return d.get(ref_key, {}).get('value')

print(get_value(r, '6', '3', 'Conversion'))

Doing it this way offers the flexibility of specifying the relevant keys and value

  • Related