user62054
user62054

Reputation: 49

Access Python dict with wildcard key element

Given the dict (fragment below), the structure will always be the same, but the key-name 'private' may change name, and I have no independent way to know what will be the value of 'private' part of the key.

json = simplejson.loads(open('servers.list', 'r').read())
for server in json['servers']:
{
    "servers": [
        {
            "addresses": {
                "private": [
                    {
                        "addr": "10.2.198.244",
                        "version": 4
                    },
                    {
                        "addr": "10.4.189.211",
                        "version": 4
                    }
                ]
            }
        }
    ]
}

How do I reference 'addr'?

in general, this will work, but it is not a way to replace 'private' with wildcard:

addr0 = server.get('addresses').get(‘private')[0].get('addr’)

Upvotes: 3

Views: 2845

Answers (1)

mhawke
mhawke

Reputation: 87084

For the one off selection of address 0 in this very contrived example:

>>> addr0 = json['servers'][0]['addresses'].values()[0][0]['addr']
>>> addr0
'10.2.198.244'

More generally it is difficult to say.

To what does the key private change? Would it be public by any chance? It looks like there could be other types of address (e.g. public) that might be present in the addresses dict. You can not assume a particular order of keys in the dictionary, which means that you can't rely on dict.values() returning the private addresses at list index 0. It is unpredictable without a reliable key.

Upvotes: 1

Related Questions