【问题标题】:Python: recursively append dictionary to anotherPython:递归地将字典附加到另一个
【发布时间】:2021-08-31 18:11:42
【问题描述】:

我已经搜索并找到了这个Append a dictionary to a dictionary,但是如果它们存在于a 中,那么它会破坏来自b 的键..

我想基本上递归地将 1 个字典附加到另一个,其中:

  • 键是唯一的(显然,它是一个字典),但每个字典都在结果中完全表示,因此 a.keys() 和 b.keys() 都是 c.keys() 的子集
  • 如果相同的键在两个字典中,则生成的键包含来自两者的值列表,例如a[key] 和b[key] 在c[key]
  • 值可以是另一个字典,(但不超过 1 级),在这种情况下,应该应用相同的逻辑(附加值),使得 a[key1][key2] 和 b[key1][key2] 在 c[key][key2]

基本示例是 2 个字典的键不重叠,我可以通过多种方式实现这一点。例如,c = {**a, **b},所以我没有在下面介绍

一个更棘手的案例:

a = {
   "key1": "value_a1"
   "key2": "value_a2"
}

b = { 
   "key1": "value_b1"
   "key3": "value_b3"
}

c = combine(a, b)

c >> {
   "key1": ["value_a1", "value_b1"],
   "key2": "value_a2",
   "key3": "value_b3"
}

一个更棘手的案例

a = {
   "key1": {
      "sub_key_1": ["sub_value_a1", "sub_value_a2"],
      "sub_key_2": "sub_value_a3"
   },
   "key2": "value_a2"
}

b = { 
   "key1": {
      "sub_key_1": ["sub_value_a1", "sub_value_b1"],
      "sub_key_2": "sub_value_b3"
   },
   "key3": "value_b3"  # I'm okay with converting this to a list even if it's not one
}

c = combine(a, b)

c >> {
   "key1": {
      "sub_key_1": ["sub_value_a1", "sub_value_a2", "sub_value_b1"],  #sub_value_a1 is not duplicated
      "sub_key_2": ["sub_value_a3", "sub_value_b3"]
   },
   "key2": "value_a2",
   "key3": "value_b3" # ["value_b3"] this would be okay, following from the code comment above
}

注意事项:

  • Python 3.6
  • 这些示例显示了按需要创建的列表,但我可以接受每个非字典值都是一个列表,如代码 cmets 中所述
  • 列表中的值始终是字符串

我尽力解释,但如果需要可以详细说明。这几天一直在努力,一直卡在子关键部分

【问题讨论】:

  • 当a["key1"] 是dict 而b["key1"] 是str 或list 时会发生什么?
  • 您对此任务的具体问题是什么? “我一直卡住”不是问题。
  • 是的,我没有提到字典只会与字典合并,而不是列表或字符串。我的问题是“我将如何最好地解决这个问题?”

标签: python dictionary recursion


【解决方案1】:
a = {
   "key1": "value_a1",
   "key2": "value_a2"
}
b = { 
   "key1": "value_b1",
   "key3": "value_b3"
}
def appendValues(ax,cx):
    if type(ax)==list:#is key's value in a, a list?
        cx.extend(ax)#if it is a list then extend
    else:#key's value in a, os not a list
        cx.append(ax)#so use append
    cx=list(set(cx))#make values unique with set
    return cx
    
def combine(a,b):
    c={}
    for x in b:#first copy b keys and values to c
        c[x]=b[x]
    for x in a:#now combine a with c
        if not x in c:#this key is not in c
            c[x]=a[x]#so add it
        else:#key exists in c
            if type(c[x])==list:#is key's value in c ,a list?
                c[x]=appendValues(a[x],c[x])
            elif type(c[x])==dict:#is key's value in c a dictionary?
                c[x]=combine(c[x],a[x])#combine dictionaries
            else:#so key';'s value  is not list or dict
                c[x]=[c[x]]#make value a list
                c[x]=appendValues(a[x],c[x])
    return c
c = combine(a, b)
print(c)
print("==========================")
a = {
   "key1": {
      "sub_key_1": ["sub_value_a1", "sub_value_a2"],
      "sub_key_2": "sub_value_a3"
   },
   "key2": "value_a2"
}

b = { 
   "key1": {
      "sub_key_1": ["sub_value_a1", "sub_value_b1"],
      "sub_key_2": "sub_value_b3"
   },
   "key3": "value_b3"  # I'm okay with converting this to a list even if it's not one
}

c = combine(a, b)
print(c)

【讨论】:

    【解决方案2】:

    听起来你想要一个专门的 dict 版本。因此,您可以将其子类化以提供您想要的行为。作为一个 Python 菜鸟,我从这里开始回答:Subclassing Python dictionary to override __setitem__

    然后我在你的几个例子中添加了行为。

    我还添加了一个 MultiValue 类,它是列表的子类。这可以很容易地判断 dict 中的值是否已经有多个值。它还会删除重复项,因为看起来您不想要它们。

    class MultiValue(list):
        # Class to hold multiple values for a dictionary key. Prevents duplicates.
    
        def append(self, value):
            if isinstance(value, MultiValue):
                for v in value:
                    if not v in self:
                        super(MultiValue, self).append(v)
            else:
                super(MultiValue, self).append(value)
    
    
    class MultiValueDict(dict):
        # dict which converts a key's value to a MultiValue when the key already exists.
        
        def __init__(self, *args, **kwargs):
            self.update(*args, **kwargs)
    
        def __setitem__(self, key, value):
            # optional processing here
            if key in self:
                existing_value = self[key]
                if isinstance(existing_value, MultiValueDict) and isinstance(value, dict):
                    existing_value.update(value)
                    return
                if isinstance(existing_value, MultiValue):
                    existing_value.append(value)
                    value = existing_value
                else:
                    value = MultiValue([existing_value, value])
            super(MultiValueDict, self).__setitem__(key, value)
    
        def update(self, *args, **kwargs):
            if args:
                if len(args) > 1:
                    raise TypeError("update expected at most 1 arguments, "
                                    "got %d" % len(args))
                other = dict(args[0])
                for key in other:
                    self[key] = other[key]
            for key in kwargs:
                self[key] = kwargs[key]
    
        def setdefault(self, key, value=None):
            if key not in self:
                self[key] = value
            return self[key]
    

    示例 1:

    a = {
        "key1": "value_a1",
        "key2": "value_a2"
    }
    
    b = {
        "key1": "value_b1",
        "key3": "value_b3"
    }
    
    # combine by creating a MultiValueDict then using update to add b to it.
    c = MultiValueDict(a)
    c.update(b)
    
    print(c)
    # gives {'key1': ['value_a1', 'value_b1'], 'key2': 'value_a2', 'key3': 'value_b3'}
    

    示例 2:key1 的值是作为 MultiValueDict 创建的,而 sub_key_1 的值是 MultiValue,因此这可能不适合您尝试执行的操作。这取决于您如何构建数据集。

    a = {
        "key1": MultiValueDict({
            "sub_key_1": MultiValue(["sub_value_a1", "sub_value_a2"]),
            "sub_key_2": "sub_value_a3"
        }),
        "key2": "value_a2"
    }
    
    b = {
        "key1": MultiValueDict({
            "sub_key_1": MultiValue(["sub_value_a1", "sub_value_b1"]),
            "sub_key_2": "sub_value_b3"
        }),
        "key3": "value_b3"  # I'm okay with converting this to a list even if it's not one
    }
    
    c = MultiValueDict(a)
    c.update(b)
    
    print(c)
    # gives {'key1': {'sub_key_1': ['sub_value_a1', 'sub_value_a2', 'sub_value_b1'], 'sub_key_2': ['sub_value_a3', 'sub_value_b3']}, 'key2': 'value_a2', 'key3': 'value_b3'}
    

    【讨论】:

      【解决方案3】:

      没有简单的内置方法可以做到这一点,但您可以在 python 中重新创建逻辑。

      def combine_lists(a: list, b: list) -> list:
          return a + [i for i in b if i not in a]
      
      def combine_strs(a: str, b: str) -> str:
          if a == b:
              return a
          return [a, b]
      
      class EMPTY:
          "A sentinel representing an empty value."
      
      def combine_dicts(a: dict, b: dict) -> dict:
          output = {}
          keys = list(a) + [k for k in b if k not in a]
          for key in keys:
              aval = a.get(key, EMPTY)
              bval = b.get(key, EMPTY)
              if isinstance(aval, list) and isinstance(bval, list):
                  output[key] = combine_lists(aval, bval)
              elif isinstance(aval, str) and isinstance(bval, str):
                  output[key] = combine_strs(aval, bval)
              elif isinstance(aval, dict) and isinstance(bval, dict):
                  output[key] = combine_dicts(aval, bval)
              elif bval is EMPTY:
                  output[key] = aval
              elif aval is EMPTY:
                  output[key] = bval
              else:
                  raise RuntimeError(
                      f"Cannot combine types: {type(aval)} and {type(bval)}"
                  )
          return output
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-17
        • 2022-07-18
        • 2013-08-09
        • 2021-03-04
        • 2017-04-10
        • 2022-01-17
        相关资源
        最近更新 更多