在python中合并两个dict,不允许重复

2024-05-28 23:36:59 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题与类似的字典合并问题的不同之处在于,冲突的重复项应该失败,或者返回False。其他解决方案使用优先规则来决定如何管理一个键可能映射到两个不同的变量。在

如何在python中有效地合并两个dict。例如,考虑:

d1 = {'x': 'a', 'y': 'b', 'z': 'c'}
d2 = {'z': 'c', 'w': 'r'}
d3 = {'z': 'd', 'w': 'r'}

因此,合并字典1和字典2的结果是

^{pr2}$

但是1和3或2和3的合并应该失败,因为z有冲突。在

我的解决方案是:

def merge_dicts(d1,d2):
   k1=d1.keys()
   k2=d2.keys()
   unified_dict=dict()
   for k in k1:
       # look up in second dictionary
      if k in k2:
         pt=d2[k]  #pt stands for 'plain text'
         # if lookup is a contradiction, return empty dictionary
         #  don't even bother with partial results
         if pt!=d1[k]:
             return dict()
         else:
             unified_dict[k]=d1[k]  # safe: key is consistent
      else:
          unified_dict[k]=d1[k] # safe:  no key in k2

# get the rest
# already resolved intersection issues so just get set difference
   for k in d2.keys():
      if k not in d1.keys():
          unified_dict[k]=d2[k]

   return unified_dict

有什么改进吗?在


Tags: inptfordictionaryreturnif字典k2
3条回答

在这里使用dictionary views;它们允许您将字典键视为集合:

def merge_dicts(d1, d2):
    try:
        # Python 2
        intersection = d1.viewkeys() & d2
    except AttributeError:
        intersection = d1.keys() & d2

    if any(d1[shared] != d2[shared] for shared in intersection):
        return {}  # empty result if there are conflicts

    # leave the rest to C code, execute a fast merge using dict()
    return dict(d1, **d2)

上面的代码只测试引用不匹配值的共享键;合并本身最好留给dict()函数处理。在

我使函数在python2和python3上都能工作;如果只需要支持其中一个,请删除try..except,并用相关表达式替换{}。在Python3中,dict.keys()方法默认返回字典视图。在

可以想象,这是一个单行线;Python 3版本:

^{pr2}$

演示:

>>> d1 = {'x': 'a', 'y': 'b', 'z': 'c'}
>>> d2 = {'z': 'c', 'w': 'r'}
>>> d3 = {'z': 'd', 'w': 'r'}
>>> merge_dicts(d1, d2)
{'y': 'b', 'x': 'a', 'z': 'c', 'w': 'r'}
>>> merge_dicts(d1, d3)
{}
>>> merge_dicts(d2, d3)
{}
d1 = {'x': 'a', 'y': 'b', 'z': 'c'}                                                             
d2 = {'z': 'c', 'w': 'r'}
d3 = {'z': 'd', 'w': 'r'}

def dict_merge(d1, d2):
    """docstring for merge"""
    # doesn't work with python 3.x. Use keys(), items() instead
    if len(d1.viewkeys() & d2) != len(d1.viewitems() & d2.viewitems()):
        return {}
    else:
        result = dict(d1, **d2)
        return result

if __name__ == '__main__':
    print dict_merge(d1, d2)

稍有不同的方法(预检查):

d1={'x':'a','y':'b','z':'c'}
d2={'z':'c','w':'r'}
d3={'z':'d','w':'r'}

def merge(d1, d2):
    for (k1,v1) in d1.items():
        if k1 in d2 and v1 != d2[k1]:
            raise ValueError
    ret = d1.copy()
    ret.update(d2)
    return ret

print(merge(d1,d2))
print(merge(d1,d3))

相关问题 更多 >

    热门问题