diff --git a/Lib/plistlib.py b/Lib/plistlib.py
index 93f3ef5e38af843..5617e64161c8435 100644
--- a/Lib/plistlib.py
+++ b/Lib/plistlib.py
@@ -243,7 +243,8 @@ def end_dict(self):
self.stack.pop()
def end_key(self):
- if self.current_key or not isinstance(self.stack[-1], dict):
+ if (self.current_key or not self.stack
+ or not isinstance(self.stack[-1], dict)):
raise ValueError("unexpected key at line %d" %
self.parser.CurrentLineNumber)
self.current_key = self.get_data()
diff --git a/Lib/test/test_plistlib.py b/Lib/test/test_plistlib.py
index b9c261310bb5670..9898ec0ce572b15 100644
--- a/Lib/test/test_plistlib.py
+++ b/Lib/test/test_plistlib.py
@@ -857,6 +857,13 @@ def test_invalidarray(self):
self.assertRaises(ValueError, plistlib.loads,
("%s"%i).encode())
+ def test_invalidkey(self):
+ for xml in (b"x",
+ b'x',
+ b"x"):
+ with self.subTest(xml=xml):
+ self.assertRaises(ValueError, plistlib.loads, xml)
+
def test_invaliddict(self):
for i in ["kcompound key",
"single key",
diff --git a/Misc/NEWS.d/next/Library/2026-07-03-15-30-00.gh-issue-152959.Kx7Qm2.rst b/Misc/NEWS.d/next/Library/2026-07-03-15-30-00.gh-issue-152959.Kx7Qm2.rst
new file mode 100644
index 000000000000000..9640eafa7a8aa33
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-07-03-15-30-00.gh-issue-152959.Kx7Qm2.rst
@@ -0,0 +1,2 @@
+:mod:`plistlib` now raises :exc:`ValueError` for a ```` outside a
+```` in an XML plist. Patch by tonghuaroot.