5

I can not access the dictionary keys with dot(.) but when I define a class that inherits from dict, I can access its keys using dot(.). Can anybody explain it?

So, when I run this code:

d = {'first_key':1, 'second_key':2}
d.first_key

I get this error:

'dict' object has no attribute 'first_key'

but when I run this:

class DotDict(dict):
    pass
d = DotDict()
d.first_key = 1
d.second_key = 2
print(d.first_key)
print(d.second_key)

I get this:

1
2
16
  • 6
    Because at that point you're just creating member variables and not necessary adding to the dictionary (in the second example) Commented May 20, 2018 at 5:25
  • 1
    You have to add certain magic methods to get that functionality: stackoverflow.com/questions/2352181/… Commented May 20, 2018 at 5:26
  • 1
    For example, in the second case, if you try to do d['first_key'], you will get a KeyError Commented May 20, 2018 at 5:29
  • 4
    You should test your example without inheriting from dict. Commented May 20, 2018 at 5:30
  • 6
    This question doesn't deserve all these downvotes. It is properly formulated. And just because something might be obvious for someone, doesn't mean it is for someone else. OP even provided their exploration about the problem Commented May 20, 2018 at 5:41

3 Answers 3

4

By applying your example

class DotDict(dict):
    pass

d = DotDict()
d.first_key = 1
d.second_key = 2
print(d.first_key)
print(d.second_key)

you set instance parameters first_key and second_key to your DotDict class but not to the dictionary itself. You can see this, if you just put your dictionary content to the screen:

In [5]: d
Out[5]: {}

So, it is just an empty dict. You may access dictionaries the common way:

In [1]: d={}

In [2]: d['first'] = 'foo'

In [3]: d['second'] = 'bar'

In [4]: d
Out[4]: {'first': 'foo', 'second': 'bar'}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your consideration.
2

in the first case, you are creating keys and values belonging to a dictionary object. while in the second, you are creating attributes of a class which has nothing to do with the dictionary parent class you inherited.

1 Comment

That is a precious point. Thanks.
1

If you want to access the dict elements need to access through keys.

d['first_key']

Output:

1

If you want to access using (.) then use get.

Using get you can get the required value

d = {'first_key':1, 'second_key':2}
print(d.get('first_key'))

Output:

1

With respect to class you are accessing the attributes of class. So you will have to access using (.)

3 Comments

@pythinker: This works well. I tested it
Thanks for your help
@pythinker: So it worked. That's great. Please confirm the answer so that it will help for others

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.