加入Key上的Dicts列表

时间:2015-06-10 03:37:52

标签: python dictionary

我的清单是这样的:

l = [
        [{'g':'A','t':[]}, {'g':'C','t':['eaa']}, {'g':'B','t':['qe']}],
        [{'g':'A','t':[]}, {'g':'K','t':['ac']}, {'g':'B','t':['qs']}],
        [{'g':'A','t':[]}, {'g':'C','t':['ar']}, {'g':'B','t':['qdw']}],
        [{'g':'B','t':['eeq']}, {'g':'C','t':['eaa']}, {'g':'B','t':['zaa']}]
    ]

通过检查字典键'g'中的相等序列,我想加入每个子列表中每个字典的键't'上的列表:

l = [
        [{'g':'A','t':[]},{'g':'C','t':['eaa','ar']},{'g':'B','t':['qe','qdw']}],
        [{'g':'A','t':[]},{'g':'K','t':['ac']},{'g':'B','t':['qs']}],
        [{'g':'B','t':['eeq']},{'g':'C','t':['eaa']},{'g':'B','t':['zaa']}]
    ]

在每个列表中,选中键'g' - 如果值相等,例如('A' 'C' 'B' and 'A' 'C' 'B')然后加入't'的值。

我的代码就像这样

for i,j in l:
   count = 0
   if len(i) == len(j):
      for k in range(len(i)):
         if i[k]['g'] == j[k]['g']
            count += 1
            if count == len(i):
               i[k]['t'].append(j[k]['t'])
               del(j)
   else:
      continue

然后错误消息为ValueError: too many values to unpack

1 个答案:

答案 0 :(得分:0)

试试这个

skip = set([])
for i in range(len(l)):
    cur = l[i]
    if i not in skip:
        for j in range(i+1, len(l)):
            new, flag = l[j], True
            for k in range(len(cur)):
                if cur[k]['g'] != new[k]['g']:
                    flag = False
                    break
            if flag:
                skip.add(j)
                for k in range(len(cur)):
                    cur[k]['t'] += new[k]['t']
for i in sorted(list(skip), reverse = True):
    l.pop(i)

在迭代它们时,不能同时删除列表,字典或其他此类集合中的值。这就是您的代码出错的原因。