Jason TK
Jason TK

Reputation: 265

Double asterisks error: Invalid Syntax

Original Question here

I want to sum the [qty] based on [pid][dbid][eid][sid].

this code works on v3.6.4 but when i migrate to v3.4, then i got an error message:

new_d =  [ [{'pid': 146, 'dbid': 1, 'eid': 6212, 'qty': 10, 'sid': 6}, {'pid': 146, 'dbid': 1, 'eid': 6212, 'qty': 20, 'sid': 6}],
           [{'pid': 232, 'dbid': 1, 'eid': 6212, 'qty': 1, 'sid': 56}, {'pid': 232, 'dbid': 1, 'eid': 6212, 'qty': 1, 'sid': 56}],
           [{'pid': 146, 'dbid': 1, 'eid': 6212, 'qty': 100, 'sid': 56}, {'pid': 146, 'dbid': 1, 'eid': 6212, 'qty': 100, 'sid': 56}]]

final_result = [{**i[0], **{'qty':sum(b['qty'] for b in i)}} for i in new_d]
                  ^
       SyntaxError: invalid syntax

Upvotes: 2

Views: 2540

Answers (1)

tdelaney
tdelaney

Reputation: 77407

** can be used to unpack dictionaries into keyword arguments in function calls. Beginning with python 3.5, PEP 448 -- Additional Unpacking Generalizations was added to the language. This expands the places where you can unpack tuples (*some_tuple) and dictionaries (**some_dict).

In

{**i[0], **{'qty':sum(b['qty'] for b in i)}}

i[0] is the first dict in the list and {'qty':sum(b['qty'] for b in i)} is a dict with one key that sums the 'qty' values in the list. The ** operator unpacks both dictionaries and since the dictionary constructor now supports an arbitrary number of unpackings, the two dictionaries are merged into one.

This can all be done with a function for python 3.4 and earlier

def d_summary(d_list):
    summary = d_list[0].copy()
    summary['qty'] = sum(b['qty'] for b in d_list)
    return summary

final_result = [d_summary(i) for i in new_d]

Upvotes: 5

Related Questions