简体   繁体   English

Python Sum字典元素(更好的pythonic方式)

[英]Python Sum dictionary elements (better pythonic way)

I wrote simple few lines of code to sum elements of python dictionary to make it uniqe. 我写了简单的几行代码来求和python字典中的元素,使它唯一。

test =  [{'id': 3L, 'category': 'BOOK', 'information': 'abcdefghijk', 'name': 'test', 'sum': 5},
      {'id': 3L, 'category': 'BOOK', 'information': 'abcdefghijk', 'name': 'test', 'sum': 1},
      {'id': 3L, 'category': 'BOOK', 'information': 'abcdefghijk', 'name': 'test', 'sum': 3},
      {'id': 4L, 'category': 'BOOK', 'information': 'abcdefghijk', 'name': 'test2', 'sum': 1},
      {'id': 4L, 'category': 'BOOK', 'information': 'abcdefghijk', 'name': 'test2', 'sum': 1},
      {'id': 5L, 'category': 'BOOK', 'information': 'abcdefghijk', 'name': 'test4', 'sum': 1},
      {'id': 6L, 'category': 'BOOK', 'information': 'abcdefghijk', 'name': 'test5', 'sum': 1}]

newlist = []
newdict = {}

for dict_item in test:

    pixel = dict_item['id']
    country = dict_item['category']
    ac = dict_item['information']
    name = dict_item['name']
    sum = dict_item['sum']

    if newdict.has_key(pixel):

        pos = newdict[pixel]
        newlist[pos] = {'id': pixel, 'category': country, 'information': ac, 'name': name, 'sum': (newlist[pos]['sum']+sum)}
    else:
        newlist.append(dict_item)
        newdict[pixel] = len(newlist) -1

print newlist

Result of my sum: 我的总和结果:

   [{'category': 'BOOK', 'information': 'abcdefghijk', 'sum': 9, 'id': 3L, 'name': 'test'},{'category': 'BOOK', 'information': 'abcdefghijk', 'sum': 2, 'id': 4L, 'name': 'test2'},{'category': 'BOOK', 'information': 'abcdefghijk', 'sum': 2, 'id': 5L, 'name': 'test5'}]

Is there a better way to sum this dictionary to sum id to be unique? 有没有更好的方法可以将此字典求和以使id求和为唯一?

No need to recreate the entire dictionary with all its keys and values. 无需使用其所有键和值重新创建整个字典。 Just use dict to create a copy of the original dictionary or add to the sum of the dictionary existing in the list. 只需使用dict创建原始字典的副本或添加到列表中现有字典的总和即可。 Also, you can derive the newlist from the newdict . 此外,您还可以得出newlistnewdict

newdict = {} # or collections.OrderedDict() if order is important
for dict_item in test:
    pixel = dict_item['id']
    if pixel in newdict:
        newdict[pixel]["sum"] += dict_item['sum']
    else:
        newdict[pixel] = dict(dict_item)
newlist = list(newdict.values())

I would do it like this. 我会这样做。 Basically, combine all dicts that have the same id. 基本上,合并所有具有相同ID的字典。 I'm also sticking with a dict instead of a list so that you can easily pick out the mapping from key to values. 我还坚持使用字典而不是列表,以便您可以轻松地选择从键到值的映射。

squashed = {}
for inner in test:
    key = inner['id']
    del inner['id']
    if key in squashed:
        squashed[key]['sum'] += inner['sum']
    else:
        squashed[key] = inner
test =  [{'id': 3937L, 'category': 'BOOK', 'information': 'abcdefghijk', 'name': 'test', 'sum': 5},
      {'id': 3937L, 'category': 'BOOK', 'information': 'abcdefghijk', 'name': 'test', 'sum': 1},
      {'id': 3937L, 'category': 'BOOK', 'information': 'abcdefghijk', 'name': 'test', 'sum': 3},
      {'id': 4215L, 'category': 'BOOK', 'information': 'abcdefghijk', 'name': 'test2', 'sum': 1},
      {'id': 4215L, 'category': 'BOOK', 'information': 'abcdefghijk', 'name': 'test2', 'sum': 1},
      {'id': 4217L, 'category': 'BOOK', 'information': 'abcdefghijk', 'name': 'test4', 'sum': 1},
      {'id': 4218L, 'category': 'BOOK', 'information': 'abcdefghijk', 'name': 'test5', 'sum': 1}]

dct = {}

for d in test:
    if d["id"] in dct:
        dct[d["id"]]["sum"] += d["sum"]
    else:
        dct[d["id"]] = d.copy()

from pprint import pprint as pp

pp(dct.values())

Output matches running your own code: 输出匹配运行您自己的代码:

[{'category': 'BOOK',
  'id': 4217L,
  'information': 'abcdefghijk',
  'name': 'test4',
  'sum': 1},
 {'category': 'BOOK',
  'id': 3937L,
  'information': 'abcdefghijk',
  'name': 'test',
  'sum': 9},
 {'category': 'BOOK',
  'id': 4218L,
  'information': 'abcdefghijk',
  'name': 'test5',
  'sum': 1},
 {'category': 'BOOK',
  'id': 4215L,
  'information': 'abcdefghijk',
  'name': 'test2',
  'sum': 2}]

You can simply call dict.copy() to create new dicts, you don't need to create a new dict manually each time. 您可以简单地调用dict.copy()来创建新的字典,而无需每次都手动创建新的字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM