Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

python - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

** 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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...