【发布时间】:2017-05-11 15:18:35
【问题描述】:
我有一本这样的字典:
d = {}
d['key1'] = [('tuple1a', 'tuple1b', ['af1', 'af2', 'af3']),
('tuple2a', 'tuple2b', ['af4', 'af5', 'af6']),
('tuple3a', 'tuple3b', ['af7', 'af8', 'af9'])]
我想编写一个函数来更新值的列表部分(例如['af1','af2','af3'])。下面的代码用于过滤不同的值,以获取值中的正确列表:
def update_dict(dictionary, key, tuple_a, tuple_b, new_list=None):
for k,v in dictionary.items():
if key in k:
for i in v:
if tuple_a in i:
if tuple_b in i:
#di.update(i[2], new_lst) #this is what I'd like to do but can't get the right syntax
return dictionary
我想添加类似di.update(i[2], new_lst) 的内容我的问题是如何仅使用新列表更新列表值?
【问题讨论】:
-
它是一个元组字典。您不能更新元组。但我想知道您是否可以单独更改推荐列表。
-
由于元组是不可变的,我可以像这样重新创建字典:
d.update({k: [(tuple_a, tuple_b, aod_nt)]})但它创建的字典只有一个键:值对。如何保留字典中的其他值? -
我在 Stackoverflow 上的其他地方 posted an answer 描述了如何更改字典中列表中的值。
标签: python python-3.x dictionary tuples