比较指标,更新不覆盖值

时间:2019-10-29 10:33:03

标签: python dictionary

不是正在寻找这样的东西:

How do I merge two dictionaries in a single expression?

Generic way of updating python dictionary without overwriting the subdictionaries

Python: Dictionary merge by updating but not overwriting if value exists

正在寻找这样的东西:

输入:

d1 = {'a': 'a', 'b': 'b'}
d2 = {'b': 'c', 'c': 'd'}

输出:

new_dict = {'a': ['a'], 'b': ['b', 'c'], 'c': ['d']}

我有以下代码有效,但我想知道是否有更有效的方法:

首先,我创建一个列表“ unique_vals”,其中存储了两个字典中存在的所有值。 由此,将创建一个新字典,该字典存储两个词典中存在的所有值

unique_vals = []
new_dict = {}
for key in list(d1.keys())+list(d2.keys()) :
    unique_vals = []
    try:
        for val in d1[key]:
            try:
                for val1 in d2[key]:
                    if(val1 == val) and (val1 not in unique_vals):
                        unique_vals.append(val)
            except:
                continue
    except:        
        new_dict[key] = unique_vals
    new_dict[key] = unique_vals

然后,对于这本新词典中未列出的两个词典中的每个值,这些值都将附加到新词典中。

for key in d1.keys():
      for val in d1[key]:
          if val not in new_dict[key]:
              new_dict[key].append(val)
for key in d2.keys():
    for val in d2[key]:
        if val not in new_dict[key]:
            new_dict[key].append(val)

3 个答案:

答案 0 :(得分:3)

也许带有context

defaultdict

这适用于>>> d1 = {'a': 'a', 'b': 'b'} >>> d2 = {'b': 'c', 'c': 'd'} >>> from collections import defaultdict >>> >>> merged = defaultdict(list) >>> dicts = [d1, d2] >>> for d in dicts: ...: for key, value in d.items(): ...: merged[key].append(value) ...: >>> merged defaultdict(list, {'a': ['a'], 'b': ['b', 'c'], 'c': ['d']}) 列表中的任意数量的字典。

功能:

dicts

答案 1 :(得分:3)

这是一个简单得多的版本:

    $scope.upload = function () {
        var doc = document.getElementById($scope.pathSource);
        doc.onclick = function () {
            if (doc.value || $scope.isIE9) {
                try {
                    doc.value = "";
                } catch (err) { }
                if (doc.value) { 
                    var form = document.createElement("form"),
                        parentNode = doc.parentNode, ref = doc.nextSibling;
                    form.appendChild(doc);
                    form.reset();
                    parentNode.insertBefore(doc, ref);
                }
            }
        };
        doc.onchange = function () {
            if (!$scope.isIE9) {
                var path = angular.element("#" + $scope.pathSource).val();
                angular.element("#" + $scope.pathId).val(path);
                if ($scope.setCount)
                    $scope.setCount(doc.files.length);
            }
        };
        doc.click();
    }
}

输出:

d1 = {'a': 'a', 'b': 'b'}
d2 = {'b': 'c', 'c': 'd'}

new_dict = {key: [value] for key, value in d1.items()}
for key, value in d2.items():
    try:
        new_dict[key].append(value)
    except:
        new_dict[key] = [value]

答案 2 :(得分:2)

编辑:下面的解决方案是针对原始问题的,请参见其他答案,或针对更新的问题进行重复。

一种解决方案:

def merge_dicts(*dcts):
    return {k: [d[k] for d in dcts if k in d] for k in {k for d in dcts for k in d.keys()}}

d1 = {'a': 'a', 'b': 'b'}
d2 = {'b': 'c', 'c': 'd'}
print(merge_dicts(d1, d2))
# {'c': ['d'], 'a': ['a'], 'b': ['b', 'c']}