TypeErrer : 'method' object is not subscriptable in streamlit

Dear Sir

I have encountered an error in my code related to a for loop, which does not recognize the array list. Please review my code and the error message, and provide the correct code along with a solution.

import streamlit as st

from streamlit_dnd import dnd, apply_move

# 1. Initialize your list in session state

if “items” not in st.session_state:

st.session_state.items = {

    "list": \["Item 1", "Item 2", "Item 3"\]

}

# 2. Render the elements in your Streamlit containers

with st.container(key=“my_container”):

for item in st.session_state.items\["list"\]:     

    with st.container(key=f"item\_{item}"):

        st.write(item)

# 3. Capture the drag and drop event (must be called AFTER rendering)

event = dnd(“my_container”)

# 4. Apply the move to session state

if event:

apply_move(event, st.session_state.items)

st.rerun()

Welcome to the Streamlit community and thanks for sharing your code and error! :blush: The error 'method' object is not subscriptable happens because st.session_state.items is actually a method of Python dictionaries, not your intended session state variable. This is due to a naming conflict: items is a built-in method for dictionaries, so using it as a key in st.session_state causes confusion.

Solution:
Change your session state key from items to something else, like my_items. Here’s the corrected code:

import streamlit as st
from streamlit_dnd import dnd, apply_move

# 1. Initialize your list in session state
if "my_items" not in st.session_state:
    st.session_state.my_items = {
        "list": ["Item 1", "Item 2", "Item 3"]
    }

# 2. Render the elements in your Streamlit containers
with st.container(key="my_container"):
    for item in st.session_state.my_items["list"]:
        with st.container(key=f"item_{item}"):
            st.write(item)

# 3. Capture the drag and drop event (must be called AFTER rendering)
event = dnd("my_container")

# 4. Apply the move to session state
if event:
    apply_move(event, st.session_state.my_items)
    st.rerun()

This avoids the naming conflict and should resolve your error. For more on this pattern, see the streamlit-dnd demo and docs.

Sources:

Thanks for bringing this to my attention. I will need to fix the examples I provided!