Double asterisks error: Invalid Syntax

前端 未结 1 501
迷失自我
迷失自我 2021-01-22 04:44

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:

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-22 05:36

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

    0 讨论(0)
提交回复
热议问题