2017-05-11 265 views
0

的字典替换值我有一本字典,像这样:在列表/元组蟒蛇

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)我的问题是如何以新的清单仅更新列表值?

+0

这是一个元组字典。你不能更新元组。但我想知道你可以单独更改引用列表。 – Dandekar

+0

因为元组是不可变的,所以我可以像这样重新创建字典:'d.update({k:[(tuple_a,tuple_b,aod_nt)]})'但它只创建一个关键字:值对的字典。我怎样才能保存字典中的其他值? – e9e9s

回答

1

由于元组是一个不可变类型,所以不能更改元组中的单个条目。解决方法是使用元组中的元素创建一个列表,然后从列表中创建一个元组。您也将有新的元组分配给定元素在父列表,像这样:

for k,v in dictionary.items(): 
    if key in k: 
     for n,tpl in enumerate(v): 
      if tuple_a in tpl and tuple_b in tpl: 
       v[n] = tuple(list(tpl)[:-1] + [new_list]) 

(我是你的榜样有点困惑,其中的变量称为tuple_a和tuple_b实际上串。最好称它们为name_a和name_b或类似的。)

1

正如其他提到的,你不能改变元组中的单个条目。但是元组中的列表仍然是可变的。

>>> my_tuple = ('a', 'b', 'c', [1, 2, 3, 4, 5], 'd') 
>>> my_tuple 
('a', 'b', 'c', [1, 2, 3, 4, 5], 'd') 
>>> my_tuple[3].pop() 
5 
>>> my_tuple[3].append(6) 
>>> my_tuple 
('a', 'b', 'c', [1, 2, 3, 4, 6], 'd') 

所以你想要的东西,你可以这样做:

>>> my_tuple = ('a', 'b', 'c', [1, 2, 3, 4, 5], 'd') 
>>> newList = [10, 20, 30] 
>>> 
>>> del my_tuple[3][:]  # Empties the list within 
>>> my_tuple 
('a', 'b', 'c', [], 'd') 
>>> my_tuple[3].extend(newList) 
>>> my_tuple 
('a', 'b', 'c', [10, 20, 30], 'd') 

因此,在你的代码

del i[2][:] 
i[2].extend(new_list) 

更换# di.update(i[2], new_lst)我认为这是更快了。