DEV Community

Asim Khan
Asim Khan

Posted on

Why obj['key'] Works in JavaScript but Breaks in Python

Have you ever switched between JavaScript and Python, wrote some "perfectly fine" code, and got hit with an error like:

TypeError: 'AIMessage' object is not subscriptable
Enter fullscreen mode Exit fullscreen mode

I did. And I was simply trying to access .content from a LangChain AIMessage response. Here's what happened and why it matters if you're thinking in JavaScript while writing Python.


β˜• The JavaScript Way

In JavaScript, objects are flexible:

const person = { name: "Asim" };

console.log(person.name);      // βœ… "Asim"
console.log(person["name"]);   // βœ… "Asim"
Enter fullscreen mode Exit fullscreen mode

Both dot notation and bracket notation work. You can use either depending on the context (e.g., dynamic keys with brackets).


🐍 The Python Way

In Python, it depends on the type:

# Dictionary (like JS object)
person = { "name": "Asim" }
print(person["name"])    # βœ… Works
print(person.name)       # ❌ AttributeError

# Object / Class instance
class Person:
    def __init__(self, name):
        self.name = name

p = Person("Asim")
print(p.name)            # βœ… Works
print(p["name"])         # ❌ TypeError
Enter fullscreen mode Exit fullscreen mode

So when I wrote this in Python:

print(state["messages"][-1]["content"])  # ❌ TypeError
Enter fullscreen mode Exit fullscreen mode

…it failed because state["messages"][-1] was not a dictionary. It was a LangChain AIMessage object. The fix?

print(state["messages"][-1].content)  # βœ…
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ TL;DR

Language Dot Notation Bracket Notation Notes
JavaScript βœ… obj.key βœ… obj["key"] Interchangeable
Python Dict ❌ dict.key βœ… dict["key"] Dot works only for objects
Python Obj βœ… obj.prop ❌ obj["prop"] Brackets work only for dicts

🧠 Final Thoughts

If you're coming from JavaScript and working in Python (especially with tools like LangChain), remember:

Not everything is a dictionary. And not everything can be accessed with brackets.

This subtle difference can cost hours of debugging if you’re in the zone and writing fast.

Have you faced a similar gotcha when switching languages? Let me know below πŸ‘‡


python #javascript #langchain #debugging #programmingtips

Top comments (0)