没有足够的值来解包(期望2,得到1),当循环通过dict



我有一个这样的字典列表:

zip_values = [{'Spain': '43004'}, {'Spain': '43830'}, {'Spain': '46003'}, {'Spain': '50006'}, {'Portugal': ''}, {'Portugal': '1000-155'}, {'Portugal': '1000-226'}, {'Portugal': '1050-175'}, {'Portugal': '1050-190'}, {'Portugal': '1070-041'}, {'Portugal': '1150-101'}, {'Portugal': '1150-260'}, {'Portugal': '1200-114'}, {'Portugal': '1250-192'}, {'Portugal': '1300-243'}, {'Portugal': '1300-610'}, {'Portugal': '1350-100'}, {'Portugal': '1400-140'}, {'Portugal': '1400-212'}, {'Portugal': '1400-352'}, {'Portugal': '1495-057'}, {'Portugal': '1495-135'}, {'Portugal': '1500-073'}, {'Portugal': '1500-151'}, {'Portugal': '1500-506'}, {'Portugal': '1600-161'}, {'Portugal': '1600-864'}, {'Portugal': '1700-093'}, {'Portugal': '1700-163'}, {'Portugal': '1700-239'}, {'Portugal': '1750-249'}, {'Portugal': '1750-429'}, {'Portugal': '1800-297'}, {'Portugal': '1950-130'}, {'Portugal': '1990-179'}]

但是更大。我想循环遍历它,像这样

for key, value in zip_values:
if key == "France" | key == "Germany" | key == "Spain":
current_zip = check_if_zipcodes_correct(value, 1000, 99999, 5)

check_if_zipcodes_correct是一些函数,我想使用zipcodes,但这并不重要,我得到一个错误时运行脚本:ValueError:没有足够的值来解包(期望2,得到1)

你正在尝试迭代字典列表,for key, value in zip_values将尝试将keyvalue映射到字典对象(例如:—不支持{'Spain': '43004'})。如果它是list/tuple(例如[ Spain', '43004']),它将工作。

试试这样-

for d in zip_values:
for key, value in d.items():
if key in ("France", "Germany", "Spain"):
current_zip = check_if_zipcodes_correct(value, 1000, 99999, 5)

另外,if key == "France" | key == "Germany" | key == "Spain"可以简化为if key in ("France", "Germany", "Spain")

zip_values中的每个项目都是单个'dict '对象,您不能将其解包为两个项目。您需要遍历列表并从每个字典

中获取第一个键值对。
for d in zip_values:
key, value = next(iter(d.items()))
# or
key, value = list(d.items())[0]

另外,你不能像这样使用|,你需要用括号

if (key == "France") | (key == "Germany") | (key == "Spain")

使用逻辑条件

if key == "France" or key == "Germany" or key == "Spain":

或在列表

上使用in
if key in ["France", "Germany", "Spain"]

相关内容

  • 没有找到相关文章

最新更新