作者:潇然free | 来源:互联网 | 2022-12-06 10:00
编写一个函数add_to_dict(d, key_value_pairs)
,将每个给定的键/值对添加到给定的字典中。参数key_value_pairs
将是形式为元组的列表(key, value)
。
该函数应返回所有已更改的键/值对的列表(及其原始值)。
def add_to_dict(d, key_value_pairs):
newlist = []
for key,value in d:
for x,y in key_value_pairs:
if x == key:
newlist.append(x,y)
return newlist
我不断收到错误消息
ValueError:没有足够的值可解包(预期2,得到1)
我如何完成这个问题?
1> KaiserKatze..:
您应该如何调试代码
'''
@param d: a dictionary
@param key_value_pairs: a list of tuples in the form `(key, value)`
@return: a list of tuples of key-value-pair updated in the original dictionary
'''
def add_to_dict(d, key_value_pairs):
newlist = []
for pair in key_value_pairs:
# As is mentioned by Mr Patrick
# you might not want to unpack the key-value-pair instantly
# to avoid possible corrupted data input from
# argument `key_value_pairs`
# if you can't guarantee its integrity
try:
x, y = pair
except (ValueError):
# unable to unpack tuple
tuple_length = len(pair)
raise RuntimeError('''Invalid argument `key_value_pairs`!
Corrupted key-value-pair has ({}) length!'''.format(tuple_length))
# Instead of using nesting loop
# using API would be much more preferable
v = d.get(x)
# Check if the key is already in the dictionary `d`
if v:
# You probably mean to append a tuple
# as `array.append(x)` takes only one argument
# @see: https://docs.python.org/3.7/library/array.html#array.array.append
#
# Besides, hereby I quote
# "The function should return a list of all of the key/value pairs which have changed (with their original values)."
# Thus instead of using the following line:
#
# newlist.append((x, y,))
#
# You might want a tuple of (key, old_value, new_value)
# Hence:
newlist.append((x, v, y,))
# I don't know if you want to update the key-value-pair in the dictionary `d`
# take out the following line if you don't want it
d[x] = y
return newlist
如果您想知道如何dict
正确地遍历对象,请继续阅读其余部分。
遍历
dict
对象的不同方法
Python 3.x
以下各节演示了如何dict
在Python 3.x中遍历a 。
迭代键集
for key in d:
value = d[key]
print(key, value)
the code segment above has the same effect as the following one:
for key in d.keys():
value = d[key]
print(key, value)
迭代键值对的集合
for key, value in d.items():
print(key, value)
迭代一组值
for value in d.values():
print(value)
Python 2.x
以下各节演示了如何dict
在Python 2.x中遍历a 。
迭代键集
for key in d:
value = d[key]
print(key, value)
keys()
返回字典键集的列表d
for key in d.keys():
value = d[key]
print(key, value)
iterkeys()
返回字典键集的迭代器d
for key in d.iterkeys():
value = d[key]
print(key, value)
迭代键值对的集合
values()
返回字典的键值对集合的列表d
for key, value in d.items():
print(key, value)
itervalues()
返回字典的键值对集合的迭代器d
for key, value in d.iteritems():
print(key, value)
迭代一组值
values()
返回字典值集的列表 d
for value in d.values():
print(value)
itervalues()
返回字典值集的迭代器 d
for value in d.itervalues():
print(value)
参考:
Python中的列表和迭代器有什么区别?
2> 小智..:
用于items()
解决,例如:
d = {"foo": "bar"}
for key, value in d.items():
print key, value