Python map reduce 匹配字典中的部分键和求和值
Python map reduce match partial key in Dictionary and sum values
我正在尝试根据部分键匹配对字典中的值求和。我的字典 cust_dictionary
看起来像这样,键为 month;Country:customer_id
然后值是销售额
:|{'07;EIRE:14156': 26468.0, '09;United Kingdom:16266': 102.0,'07;EIRE:12600': 124.0
我有一个部分键列表 uniq_cust
,如下所示:
:|['07;EIRE', '09;United Kingdom', '06;United Kingdom', '03;Germany', '04;Finland',
我会使用键列表遍历字典并以这种方式求和吗?那会是什么样子?
我想将部分键与字典匹配并对每个匹配项求和,这样我就会得到这样的东西:
07:EIRE,14280
09:United Kingdom,16266
result = {}
for key,dict_value in custom_dict.items():
partial_key, rest_key_value = key.split(':')
if not partial_key in result:
result[partial_key] = 0
#not super clear from your question if you want to add the numbers within the keys or the number associated to the keys via the dict
#next commented out line is adding the values included in the keys themselves
#result[partial_key] += int(rest_key_value)
#next line is adding the values in the dict
result[partial_key] += dict_value
我正在尝试根据部分键匹配对字典中的值求和。我的字典 cust_dictionary
看起来像这样,键为 month;Country:customer_id
然后值是销售额
:|{'07;EIRE:14156': 26468.0, '09;United Kingdom:16266': 102.0,'07;EIRE:12600': 124.0
我有一个部分键列表 uniq_cust
,如下所示:
:|['07;EIRE', '09;United Kingdom', '06;United Kingdom', '03;Germany', '04;Finland',
我会使用键列表遍历字典并以这种方式求和吗?那会是什么样子?
我想将部分键与字典匹配并对每个匹配项求和,这样我就会得到这样的东西:
07:EIRE,14280
09:United Kingdom,16266
result = {}
for key,dict_value in custom_dict.items():
partial_key, rest_key_value = key.split(':')
if not partial_key in result:
result[partial_key] = 0
#not super clear from your question if you want to add the numbers within the keys or the number associated to the keys via the dict
#next commented out line is adding the values included in the keys themselves
#result[partial_key] += int(rest_key_value)
#next line is adding the values in the dict
result[partial_key] += dict_value