Anvil Community Forum

Pulling from Dicts

If I have a dict like so:

test_response = {'first': 'one', 'second': 'two', 'third':'three'}

and I use the code:

test_response.third

I get an error saying

AttributeError: 'dict' object has no attribute 'third'

But it obviously does!! …Right? But when I use this code:

test_response['third']

it works!! Can someone explain to me why this is? I’m trying to better conceptually understand python and it is these little things that tend to trip me up, so I want to really understand what is happening here.

Here is a little example of what I mean, if I wasn’t clear in explaining this.
https://anvil.works/build#clone:23G6YPKFR7KOATFV=3ZUNZKUR4LWQH7LTCB3IUZCT

1 Like

Hi @chesney.l - sure thing. That’s happening because a dictionary is a Python data structure, and it doesn’t have an attribute called ‘third’. So it raises an AttributeError - it means the object (in your case the object is test_response) doesn’t have the attribute you’re asking for.

test_response does however have a key called third, and that’s what you get with test_response['third']. If instead you try to call test_response['fourth'], you’d get another kind of exception, a KeyError, because fourth is not a key in the dictionary.

Hope this helps - feel free to ask follow up questions. Welcome to Python!

3 Likes

This is a mistake I used to make often, especially when switching between Javascript which mainly does work the way you described & Python which doesn’t.

1 Like

Thank you very much @kevin and @david.wylie !!

You’re very welcome. One last bit of info you may find useful: dictionaries have a .get() method. It may make your life a bit simpler.

Normally, if you try to access a key that doesn’t exist, Python will raise a KeyError like I’d mentioned. So you’d need to catch it - usually goes something like this:

try:
    answer = test_response['fourth']
except KeyError:
    answer = 'something else instead'

I often find it convenient to use the .get() method instead because it will return the value if the key exists, and if the key doesn’t exist, it will simply the default argument you provide. So the exception handling above turns into one line:

answer = test_response.get('fourth', default='something else instead')

For Data Bindings though, I’d recommend you call keys that you know will exist.

3 Likes

This community is amazing. Again, thank you for the information!! @kevin

2 Likes