Combining two dictionaries into one with the same keys?

前端 未结 7 1754
眼角桃花
眼角桃花 2020-12-06 03:35

I\'ve looked through a few of the questions here and none of them seem to be exactly my problem. Say I have 2 dictionaries, and they are dict1

{\'A\': 25 ,          


        
7条回答
  •  太阳男子
    2020-12-06 04:16

    This is another way to do it, and will work regardless if the keys are present in only one or in both dictionaries.

    def merge_dicts(dict_a, dict_b):
        merged_dict = {key: [value] for key, value in dict_a.iteritems()}
        for key, value in dict_a.iteritems():
            try:
                merged_dict[key].append(value)
            except KeyError:
                meeged_dict[key] = [value]
        return ret_dict
    

提交回复
热议问题