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)