see the error "KeyError: 'my_container'"

Dear Sir

i use this below code it run but give one error

please see the code and error

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 is error

KeyError: ‘my_container’

File “D:\pyff\contt.py”, line 21, in
apply_move(event, st.session_state.my_items)
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\user\AppData\Local\Programs\Python\Python314\Lib\site-packages\streamlit_dnd_init_.py”, line 267, in apply_move
src = lists[event.from_container]
~~~~~^^^^^^^^^^^^^^^^^^^^^^

please see error and give me the solution

best regared

Welcome to the Streamlit community! Thanks for sharing your code and error details. :blush:

Your error happens because the key used in your st.container(key=...) (“my_container”) does not match the key in your st.session_state.my_items dictionary (“list”). The apply_move function expects the container key (“my_container”) to be present in your items dictionary, but your dictionary uses “list” as the key. To fix this, change your session state initialization to use “my_container” as the key:

import streamlit as st
from streamlit_dnd import dnd, apply_move

# 1. Initialize your list in session state
if "my_container" not in st.session_state:
    st.session_state.my_container = {
        "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_container["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_container)
    st.rerun()

This ensures the container key and the dictionary key match, resolving the KeyError. According to the streamlit-dnd documentation, the keys passed to dnd() and used in your items dictionary must be the same.

Sources: