User login

Python dictionary objects do not allow accessing of values with dot notation

Documenting this because it's the kind of frustrating mistake to solve that could drive someone away from Python entirely, yet it'll be a mistake i'll probably never make again and would be able to solve in seconds if i do.

A dictionary, or 'dict', must be accessed with bracket notation. Unlike JavaScript, dot notation is not an option for dicts.

This works:

    from activore.models import MassEmail
...
    email_data = request.get_json()
    email = MassEmail(
        message = email_data['message'],
        subject = email_data['subject'],
        status = email_data['status'],
        senderid = 2,
        venueid = 1
    )

This does not:

    email = MassEmail(
        message = email_data.message,
        subject = email_data.subject,
        status = email_data.status,
        senderid = 2,
        venueid = 1
    )

Getting JSON from the request returns a dict. Unlike other objects its attributes cannot be accessed with object.attributekey, but only with dict['attributekey'].

Though it's possible to dress up the dict to allow dot notation, it's not any particular benefit. It's just a matter of knowing why your simple dot isn't working.

http://code.activestate.com/recipes/361668/
http://docs.python.org/2/reference/datamodel.html#attribute-access
http://bytes.com/topic/python/answers/636030-dictionaries-dot-notation

Searched words: 
AttributeError: 'dict' object has no attribute 'message' dict dot notation versus brackets dict object no attribute given name AttributeError array-style notation

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.