我寫了簡單的幾行代碼來總結python字典的元素,使其成爲uniqe。Python總和字典元素(更好的pythonic方式)
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
我總和的結果:
[{'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'}]
有沒有更好的方式來總結這本字典來總結ID是唯一的?
tbh我不明白dowvotes,這似乎是一個很好的問題給我。如果downvoters可以闡述,這將是建設性的。 – Lisa
不要使用'has_key',使用'in'; 'has_key'在3.x中被棄用,而'in'則更具慣用。 – leongold
具有相同'id'但具有不同'category','information','name',...的輸入的輸出數據究竟保留什麼? – dlask