You can avoid this error if you do not iterate over the dict (of 1 million entries) but only over the list of possible changes and see if it changes anything in the dict:
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
Output:
[] # 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
You could also throw in some validation onto your parameters - if any parameter is wrong, nothing will be executed and an speaking error arises:
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
So you get clearer error messages:
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()
for x in dct
just iterate over the keys?d
tod.items()