【问题标题】:Weave two dictionaries into one将两个字典合二为一
【发布时间】:2017-06-23 19:01:36
【问题描述】:

我有两本词典:

dict1 = {'a': 1,
         'b': 2,
         'c': 3,
         'd': 4,
         'x': 5}

dict2 = {'a': 'start',
         'b': 'start',
         'c': 'end',
         'd': 'end'}

我正在尝试创建一个新字典,将值startend 作为键映射到包含dict1 信息的字典,同时保留dict2 中不存在的那些作为键,例如:

dict3 = {'start': {'a': 1, 'b': 2},
         'end': {'c': 3, 'd': 4},
         'x': {'x': 5}
        }

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    使用dict.setdefault()dict3 中创建嵌套字典(如果还没有的话),使用dict.get() 来确定顶级输出字典中的键:

    dict3 = {}
    for k, v in dict1.items():
        nested = dict3.setdefault(dict2.get(k, k), {})
        nested[k] = v
    

    因此,dict2.get(k, k) 将为来自dict1 的给定键生成来自dict2 的值,使用键本身作为默认值。所以对于'x' 键,这将产生'x',因为dict2 中没有该键的映射。

    演示:

    >>> dict3 = {}
    >>> for k, v in dict1.items():
    ...     nested = dict3.setdefault(dict2.get(k, k), {})
    ...     nested[k] = v
    ...
    >>> dict3
    {'start': {'a': 1, 'b': 2}, 'end': {'c': 3, 'd': 4}, 'x': {'x': 5}}
    

    【讨论】:

    • 可读性说明:如果您这样做,评论这是做什么的。这是以一种新颖的方式使用 setdefault ,因此如果没有某种解释就会非常神秘。
    • @TemporalWolf 这是使用dict.setdefault()按设计。我不确定它在这里的使用方式有什么新颖之处。
    • 这对你来说可能很明显,但我不清楚,我认为这是block or inline comments 适用的地方:“复杂的操作在操作之前有几行 cmets开始。不明显的会在行尾获得 cmets。"
    • @TemporalWolf:我的意思是使用dict.setdefault() 来获取键的值,如果在这样做之前设置默认值,是该方法的直接使用,但你称之为小说。也许我使用dict.setdefault() at all 对你来说是新的?至少从 Python 2.0 开始它就是标准库 dict 对象的一部分(所以 2001 年)。
    • 我的评论措辞不当:我仍然认为这作为一个反转和合并,值得评论。
    【解决方案2】:

    我实际上是在抽象示例并在这里输入我的问题时想出来的(应该早点这样做......)。无论如何:耶!

    所以这是我的解决方案,以防它可能对某人有所帮助。如果有人知道更快或更优雅的方法,我会很高兴学习!

    dict3 = dict()
    
    for k, v in dict1.items():
        # if the key of dict1 exists also in dict2
        if k in dict2.keys():
            # get its value (the keys-to-be for the new dict3)
            new_key = dict2[k]
            # if the new key is already in the new dict
            if new_key in dict3.keys():
                # appends new dict entry to dict3
                dict3[new_key].update({k: v})
            # otherwise create a new entry
            else:
                dict3[new_key] = {k: v}
        # if there is no corresponding mapping present
        else:
            # treat the original key as the new key and add to dict3
            no_map = k
            dict3[no_map] = {k: v}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-13
      • 1970-01-01
      • 2012-05-15
      • 2015-04-23
      • 1970-01-01
      相关资源
      最近更新 更多