Examples of how to add and compare the combined values of the dictionary in Python.

Source: Internet
Author: User

Examples of how to add and compare the combined values of the dictionary in Python.

Sum of dictionary merge values
When collecting and summarizing game data, some data is stored in dictionaries every day. When I want to collect statistics for multiple days, I need to merge the dictionaries.
If the keys are the same, their values are added.
The update method cannot be used, because the value of the same key is overwritten rather than the sum.
A thousand words is worse than a single code.

def union_dict(*objs):   _keys = set(sum([obj.keys() for obj in objs],[]))   _total = {}   for _key in _keys:     _total[_key] = sum([obj.get(_key,0) for obj in objs])   return _total  obj1 = {'a':1,'b':2,'c':3} obj2 = {'a':1,'b':3,'d':4} print union_dict(obj1,obj2) 

 
Output

{'a': 2, 'c': 3, 'b': 5, 'd': 4}

Sum ([obj. keys () for obj in objs], []) may not be easy to understand.
In fact, the sum () function also has "little-known Parameters", that is, the first parameter, the start parameter. The default value is 0.
It can be not only int type, but also other supporting + operators, such as [].
By using this, the layer-2 array can be flattened into a layer.
For example

>>sum([[1,2,3],[4,5]],[])[1,2,3,4,5]

Diff ("different or ")
In the game, I want to monitor and record the changes in the backpack in the item system. (The result of "exclusive or" is the same elimination, and the remaining results are different, that is, changed)
Assume that the storage structure of the backpack is like this.
Is a dictionary, {item id: quantity }.
During the initialization of the backpack class, copy and save the backpack item information to an oldbag variable, perform some item operations (such as using items and receiving item rewards), and call save () when the method is stored in redis, the new bag dictionary and oldbag dictionary are compared to get the changes.
A thousand words is worse than a single code.

def symmetric_difference(_oldobj,_newobj):   _oldkeys = _oldobj.keys()   _newkeys = _newobj.keys()   _diff = {}   for _key in set(_oldkeys + _newkeys):     _val = _newobj.get(_key,0) - _oldobj.get(_key,0)     if _val:       _diff[_key] = _val    return _diff   oldobj = {'a':1,'b':2,'c':3} newobj = {'a':1,'b':3,'d':4} print symmetric_difference(oldobj,newobj) 

Output

{'b': 1, 'd': 4,'c': -3}

This means that the player gets one 'B' item, four 'D' items, and three 'C' items.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.