如何更改字典值中的元组?

时间:2013-06-14 07:17:40

标签: python dictionary tuples

我有一个格式字典:

d[key] = [(val1, (Flag1, Flag2)),
          (val2, (Flag1, Flag2)),
          (val3, (Flag1, Flag2))]

我想成功:

d[key] = [(val1, Flag1),
          (val2, Flag1),
          (val3, Flag1)]

我该怎么做?

3 个答案:

答案 0 :(得分:8)

使用tuple解包:

d[key] = [(x, y) for (x, (y, z)) in d[key]]

答案 1 :(得分:2)

应该适用于所有项目:

d = { k: [(x, y) for (x, (y, z)) in v] for k,v in d.iteritems() }

您可能需要阅读:http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

答案 2 :(得分:1)

这应该这样做:

d[key] = [(x, y[0]) for x,y in d[key]]

简单版本:

new_val = []
for x, y in d[key]:
   #In each iteraion x is assigned to VALs and `y` is assigned to (Flag1, Flag2)
   #now append a new value, a tuple containg x and y[0](first item from that tuple) 
   new_val.append((x, y[0]))
d[key] = new_val  #reassign the new list to d[key]

修改整个字典:

dic = { k: [(x, y[0]) for x,y in v]  for k,v in dic.items()}

在py2.x中,你可以使用dic.iteritems,因为它返回一个迭代器,dic.items()将同时适用于py2x和py3x。