如果您不遍历包含100万条目的字典,而只是遍历可能更改的列表,并查看它是否会更改字典,则可以避免此错误:
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:
try:
key, value = item
except (TypeError,ValueError):
print("Unable to unpack {} into key,value".format(item))
entry = d.setdefault(key,value)
if entry != value:
newlist.append( (key, entry) )
d[key] = value
return newlist
d = {}
print(add_to_dict(d, ( (1,4), (2,5) ) ))
print(add_to_dict(d, ( (1,4), (2,5), 3 ) ))
print(add_to_dict(d, ( (1,7), (2,5), 3 ) ))
输出:
[] # 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
entry = d.setdefault(key,value)
if entry != value:
newlist.append( (key, entry) )
d[key] = value
return newlist
这样您就可以获得更清晰的错误信息:
add_to_dict({},"tata")
add_to_dict({},["tata"])
add_to_dict({},[ (1,2,3) ])
add_to_dict({},[ (1,2) ])
add_to_dict()
函数。 - user2575725for x in dct
只是遍历字典的键吗? - Ulrich Schwarzd
改为d.items()
。 - eyllanesc