-2

Pretty new to python, but pretty familiar with basic syntax, so I apologize if the description isn't completely using the correct terms.

If I have a nested dictionary called standings, which contains a value that is a dictionary called Team, which contains a value called name that can be accessed with the following:

for dicts in standings:
    print(dicts["team"]["name"])

How can I represent it like the following:

teamName = ["team"]["name"]

for dicts in standings:
    print(dicts+teamName)

so basically want to change From:

dicts["team"]["name"]

to

 dicts+variableName 

to give the same result.

Dictionary snippet:

{'rank': 1, 'team': {'id': 50, 'name': 'Manchester City'}}

I've tried a few different ways, but can't see to figure it out without getting an error, wondering if maybe it's just not possible? (although I'm sure its just a user error on my part)

Thanks!

Chase
  • 5,315
  • 2
  • 15
  • 41
Matt
  • 1
  • 1

2 Answers2

0

Your description of the data structure does not make much sense, but assuming dicts is a dictionary that contains a key team with a value that contains the key name. You can perform dynamic nested lookup using a list of keys and recursion-

def nested_lookup(d, keys):
    if len(keys) == 0:
        return d
    item = d[keys[0]]
    rest_keys = keys[1:]
    return nested_lookup(item, rest_keys)

Or, if you prefer succinct-ness, a lambda function-

nested_lookup = lambda d, ks: nested_lookup(d[ks[0]], ks[1:]) if len(ks) > 0 else d

You can use it like-

>>> nested_lookup({ 'team': { 'name': 5 } }, ['team', 'name'])
5
>>> nested_lookup({ 'team': { 'name': 5 } }, ['team'])
{'name': 5}
>>> nested_lookup({ 'team': { 'name': { 'more': [42, 47] } } }, ['team', 'name', 'more'])
[42, 47]
Chase
  • 5,315
  • 2
  • 15
  • 41
  • @Matt it seems to work fine with your snippet- `nested_lookup({'rank': 1, 'team': {'id': 50, 'name': 'Manchester City'}}, ['team', 'name'])` gives `'Manchester City'` – Chase Jan 28 '21 at 07:51
0

Similar to the previous answer, but without use of a recursion and with error handling. In case of a missing key None value will be returned.

d = {'rank': 1, 'team': {'id': 50, 'name': 'Manchester City'}}


def get_nested(d, *keys):
    result = d.copy()
    for key in keys:
        try:
            result = result[key]
        except KeyError:
            return None
    return result

print(get_nested(d, 'rank'))
print(get_nested(d, 'team', 'id'))
print(get_nested(d, 'team', 'name'))
print(get_nested(d, 'team', 'league'))
print(get_nested(d, 'non_existent', 'name'))

keys = 'team', 'name'
print(get_nested(d, *keys))

Output

1
50
Manchester City
None
None
Manchester City
Maxim Ivanov
  • 299
  • 1
  • 6