Python-如何修复“;ValueError:没有足够的值来解包(预期为2,得到1)和#x201D;
我需要编写一个函数Python-如何修复“;ValueError:没有足够的值来解包(预期为2,得到1)和#x201D;,python,dictionary,Python,Dictionary,我需要编写一个函数add_to_dict(d,key\u-value\u-pairs),将每个给定的键/值对添加到python字典中。参数key\u value\u pairs将是一个元组列表,格式为(key,value) 该函数应返回所有已更改的键/值对(及其原始值)的列表 我总是出错 ValueError:没有足够的值来解包(预期值为2,实际值为1) 如何解决此错误?使用items()解决此错误,如: d = {"foo": "bar"} for key, value in d.items
add_to_dict(d,key\u-value\u-pairs)
,将每个给定的键/值对添加到python字典中。参数key\u value\u pairs
将是一个元组列表,格式为(key,value)
该函数应返回所有已更改的键/值对(及其原始值)的列表
我总是出错
ValueError:没有足够的值来解包(预期值为2,实际值为1)
如何解决此错误?使用items()
解决此错误,如:
d = {"foo": "bar"}
for key, value in d.items():
print key, value
如何调试代码
如果您想知道如何正确地遍历dict
对象,请继续阅读剩余部分
遍历
dict
对象的不同方法
Python3.x
以下部分演示如何在Python 3.x中遍历dict
迭代密钥集
迭代键值对集
迭代值集
Python2.x 以下部分演示如何在Python2.x中遍历
dict
迭代密钥集
keys()
返回字典d
for key in d.keys():
value = d[key]
print(key, value)
for key in d.iterkeys():
value = d[key]
print(key, value)
for key, value in d.items():
print(key, value)
for key, value in d.iteritems():
print(key, value)
for value in d.values():
print(value)
for value in d.itervalues():
print(value)
iterkeys()
返回字典d
for key in d.keys():
value = d[key]
print(key, value)
for key in d.iterkeys():
value = d[key]
print(key, value)
for key, value in d.items():
print(key, value)
for key, value in d.iteritems():
print(key, value)
for value in d.values():
print(value)
for value in d.itervalues():
print(value)
迭代键值对集
values()
返回字典d
for key in d.keys():
value = d[key]
print(key, value)
for key in d.iterkeys():
value = d[key]
print(key, value)
for key, value in d.items():
print(key, value)
for key, value in d.iteritems():
print(key, value)
for value in d.values():
print(value)
for value in d.itervalues():
print(value)
itervalues()
返回字典d
for key in d.keys():
value = d[key]
print(key, value)
for key in d.iterkeys():
value = d[key]
print(key, value)
for key, value in d.items():
print(key, value)
for key, value in d.iteritems():
print(key, value)
for value in d.values():
print(value)
for value in d.itervalues():
print(value)
迭代值集
values()
返回字典d
for key in d.keys():
value = d[key]
print(key, value)
for key in d.iterkeys():
value = d[key]
print(key, value)
for key, value in d.items():
print(key, value)
for key, value in d.iteritems():
print(key, value)
for value in d.values():
print(value)
for value in d.itervalues():
print(value)
itervalues()
返回字典d
for key in d.keys():
value = d[key]
print(key, value)
for key in d.iterkeys():
value = d[key]
print(key, value)
for key, value in d.items():
print(key, value)
for key, value in d.iteritems():
print(key, value)
for value in d.values():
print(value)
for value in d.itervalues():
print(value)
参考:
def add_to_dict(d, key_value_pairs):
"""Adds all tuples from key_value_pairs as key:value to dict d,
returns list of tuples of keys that got changed as (key, old value)"""
newlist = []
for item in key_value_pairs:
# this handles your possible unpacking errors
# if your list contains bad data
try:
key, value = item
except (TypeError,ValueError):
print("Unable to unpack {} into key,value".format(item))
# create entry into dict if needed, else gets existing
entry = d.setdefault(key,value)
# if we created it or it is unchanged this won't execute
if entry != value:
# add to list
newlist.append( (key, entry) )
# change value
d[key] = value
return newlist
d = {}
print(add_to_dict(d, ( (1,4), (2,5) ) )) # ok, no change
print(add_to_dict(d, ( (1,4), (2,5), 3 ) )) # not ok, no changes
print(add_to_dict(d, ( (1,7), (2,5), 3 ) )) # not ok, 1 change
输出:
[] # ok
Unable to unpack 3 into key,value
[] # not ok, no change
Unable to unpack 3 into key,value
[(1, 4)] # not ok, 1 change
您还可以对您的参数进行一些验证-如果任何参数错误,将不会执行任何操作,并且会出现说话错误:
import collections
def add_to_dict(d, key_value_pairs):
"""Adds all tuples from key_value_pairs as key:value to dict d,
returns list of tuples of keys that got changed as (key, old value)"""
if not isinstance(d,dict):
raise ValueError("The dictionary input to add_to_dict(dictionary,list of tuples)) is no dict")
if not isinstance(key_value_pairs,collections.Iterable):
raise ValueError("The list of tuples input to add_to_dict(dictionary,list of tuples)) is no list")
if len(key_value_pairs) > 0:
if any(not isinstance(k,tuple) for k in key_value_pairs):
raise ValueError("The list of tuples includes 'non tuple' inputs")
if any(len(k) != 2 for k in key_value_pairs):
raise ValueError("The list of tuples includes 'tuple' != 2 elements")
newlist = []
for item in key_value_pairs:
key, value = item
# create entry into dict if needed, else gets existing
entry = d.setdefault(key,value)
# if we created it or it is unchanged this won't execute
if entry != value:
# add to list
newlist.append( (key, entry) )
# change value
d[key] = value
return newlist
因此,您可以获得更清晰的错误消息:
add_to_dict({},"tata")
# The list of tuples input to add_to_dict(dictionary,list of tuples)) is no list
add_to_dict({},["tata"])
# The list of tuples includes 'non tuple' inputs
add_to_dict({},[ (1,2,3) ])
# The list of tuples includes 'tuple' != 2 elements
add_to_dict({},[ (1,2) ])
# ok
请添加调用
add_to_dict()
的脚本,该脚本不会对dct中的x执行操作,只需在键上进行迭代即可?您可以指示错误发生在哪一行,并以可运行的形式提供调用函数的实例吗。i、 e将d
更改为d.items()
@ulrichswarz:是的,确实如此。因此出现了错误。