使用公共键/值在Python字典列表中求值

时间:2014-10-29 03:12:21

标签: python dictionary sum

如果已经提出这个问题,请道歉。我是一个新手,但我看了几个其他问题/答案,看起来与我的相似,但找不到一个可以解决问题的问题。我已经尝试过Counter,但似乎无法弄清楚如何保持ID键/值。

我正在尝试使用公共键/值对Python字典中的值求和。如,

list = [
    {'ID':1, 'T2':10, 'T3':20},
    {'ID':2, 'T2':5, 'T3':0},
    {'ID':1, 'T2':5, 'T3':10},
    {'ID':2, 'T2':10, 'T3':30},
    {'ID':3, 'T2':5, 'T3':0}
]

但我需要这个:

newlist = [
    {'ID':1, 'T2':15, 'T3':30}, 
    {'ID':2, 'T2':15, 'T3':30}, 
    {'ID':3, 'T2':5, 'T3':0}
]

任何帮助表示感谢。

更新:

我借用了另一个答案并尝试了这个:

superdict = {}
for d in rows:
  for k, v in d.items():
      if superdict.get(k) is None:
          superdict[k] = []
      if superdict.get(k) is not None:
          superdict[k].append(v)    

但是我没有得到一个新的组合/添加值列表,而是得到这样的结果:

'ID': ['3903', '3997', '3997', '3997', '3947', '4097', '3445', 
       '3997', '4107', '3997', '3445', '3997', '3997', '3997', 
       '3997', '3445', '3997', etc. etc.

更新2:

很抱歉我的例子很混乱。我正在寻找的是一种保持ID值静态但在字典中添加其他值的方法。因此,对应于值为1的ID的所有值都将加在一起。

E.g。这样:

list = [{'ID':1, 'T2':10, 'T3':20}, {'ID':1, 'T2':5, 'T3':10}]

成为这个:

newlist = [{'ID':1, 'T2':15, 'T3':30}]

希望这有帮助。

4 个答案:

答案 0 :(得分:3)

您很难理解您的预期结果应该与您的输入结果一致。给出预期/正确输出的具体示例。

我怀疑这就是你想要的?

my_list = [{'ID':1, 'T2':10, 'T3':20},
           {'ID':2, 'T2':5, 'T3':0}, 
           {'ID':1, 'T2':5, 'T3':10}, 
           {'ID':2, 'T2':10, 'T3':30}, 
           {'ID':3, 'T2':5, 'T3':0}]

new_dictionary = {}
for dictionary in my_list:
    for key, value in dictionary.items():
        if new_dictionary.has_key(key):
            new_dictionary[key] = value + new_dictionary[key]
        else:
            new_dictionary[key] = value

#Output:
>>>new_dictionary
{'T2': 35, 'ID': 9, 'T3': 60}

答案 1 :(得分:1)

如果我理解你的需求,这是一个解决方案:

def sum_by_common_key(input_list, index_key='ID'):
    output_dict = {}
    for d in input_list:
        index = d[index_key]
        if index not in output_dict:
            output_dict[index] = {}
        for k, v in d.items():
            if k not in output_dict[index]:
                output_dict[index][k] = v
            elif k != index_key:
                output_dict[index][k] += v
    return output_dict.values()

l = [{'ID':1, 'T2':10, 'T3':20}, {'ID':2, 'T2':5, 'T3':0}, {'ID':1, 'T2':5, 'T3':10}, {'ID':2, 'T2':10, 'T3':30}, {'ID':3, 'T2':5, 'T3':0}]
print sum_by_common_key(l)

>>> [{'T2': 15, 'ID': 1, 'T3': 30}, {'T2': 15, 'ID': 2, 'T3': 30}, {'T2': 5, 'ID': 3, 'T3': 0}]

答案 2 :(得分:1)

我希望这会对你有所帮助:

>>> from collections import Counter
>>> old_list=[{'ID':1, 'T2':10, 'T3':20}, {'ID':2, 'T2':5, 'T3':0}, {'ID':1, 'T2':5, 'T3':10}, {'ID':2, 'T2':10, 'T3':30}, {'ID':3, 'T2':5, 'T':0}]
>>> new_list=[]
>>> for i,a in enumerate(old_list):
...     z=0
...     for b in old_list[i+1:]:
...        if a['ID']==b['ID']:
...           new_list.append(dict(Counter(a)+Counter(b)))
...           new_list[-1]['ID']=a['ID']
...           temp=old_list.pop(old_list.index(b))
...           z=1
...     if not z:
...        new_list.append(a)
... 
>>> new_list
[{'T2': 15, 'ID': 1, 'T3': 30}, {'T2': 15, 'ID': 2, 'T3': 30}, {'T2': 5, 'ID': 3, 'T3': 0}]

答案 3 :(得分:0)

如果正确解释,目标是按键'ID'的值进行分组,然后对组内相应键的值求和。如果密钥是一致的,即第一个字典中的所有密钥都保证在后面的代码中显示,那么这是一个解决方案:

kotlin-gradle-plugin

输出:

my_list = [{'ID':1, 'T2':10, 'T3':20},
           {'ID':2, 'T2':5, 'T3':0}, 
           {'ID':1, 'T2':5, 'T3':10}, 
           {'ID':2, 'T2':10, 'T3':30}, 
           {'ID':3, 'T2':5, 'T3':0}]


# prep keys
id_keys = set([ z['ID'] for z in my_list ])
sum_keys = [ z for z in my_list[0].keys() if z != 'ID' ]
print('ids to group by', id_keys)
print('keys to sum over', sum_keys)

# restructure the data
big = [ [z.pop('ID'), z] for z in my_list ]
print('[[group_key, {remaining dict],] :\n', big)

# initiate results accumulator
rez = {idd: dict.fromkeys(sum_keys, 0) for idd in id_keys }
print('empty accumulator', rez)

# two loops in list comprehension
[ rez[g[0]].update({k: rez[g[0]][k] + g[1][k]}) for k in sum_keys for g in big ]
print('result', rez)

如果目标是对密钥求和,并且不保证密钥从一个字典匹配到下一个字典,请使用以下代码:

ids to group by {1, 2, 3}
keys to sum over ['T2', 'T3']
[[group_key, {remaining dict],] :
 [[1, {'T2': 10, 'T3': 20}], [2, {'T2': 5, 'T3': 0}], [1, {'T2': 5, 'T3': 10}], [2, {'T2': 10, 'T3': 30}], [3, {'T2': 5, 'T3': 0}]]
empty accumulator {1: {'T2': 0, 'T3': 0}, 2: {'T2': 0, 'T3': 0}, 3: {'T2': 0, 'T3': 0}}
result {1: {'T2': 15, 'T3': 30}, 2: {'T2': 15, 'T3': 30}, 3: {'T2': 5, 'T3': 0}}
[Finished in 0.2s]

输出:

my_list = [{'T1':1, 'T2':10, 'T3':20},
           {'T1':2, 'T2':5 , 'T3':0}, 
           {        'T2':5 ,       }, 
           {        'T2':10, 'T3':30, 'T4': 7}, 
           {'T1':3, 'T2':5 , 'T3':0 , 'T4': 3}]

rez = {}
for dic in my_list:
    for key in dic.keys():
        rez[key]=rez.setdefault(key, 0) + dic[key]

print(rez)
相关问题