简体   繁体   English

在另一个字典中合并具有相同键的python字典

[英]Merge python dicts with same key in another dict

Ex: Alias, Speed, Duplex:例如:别名、速度、双工:

Alias, Speed, Duplex are dicts with form {key: val} but in some cases Alias or Speed or Duplex may be null Alias、Speed、Duplex 是 {key: val} 形式的字典,但在某些情况下 Alias 或 Speed 或 Duplex 可能为 null

So my problem is that if I use:所以我的问题是,如果我使用:

 dd = defaultdict(list)
        for d in (Alias, Speed, Duplex):
            for key, value in d.items():
                dd[key].append(value)

I will have a result with {key: [aliasVal, speedVal, duplexVal]} but as I already told you if Alias is null I will have {key: [speedVal, duplexVal]} .我将得到{key: [aliasVal, speedVal, duplexVal]}但正如我已经告诉你的,如果 Alias 为空,我将得到{key: [speedVal, duplexVal]}

So I need to replace list with dict.所以我需要用字典替换列表。 Final result should be:最终结果应该是:

{key: {"aliasVal": aliasVal, "speedVal": speedVal, "duplexVal": duplexVal }}

And now we know keys and value if those exists现在我们知道键和值是否存在

First i want to thank you for your help but i solved this with首先我要感谢你的帮助,但我解决了这个问题

dd = defaultdict(dict)
    for d in (Alias, Descr, Speed, Duplex, adminState, opState):
        for key, value in d.items():
            dd[key].update(value)

    for elem in dd:
        """ If key doesn't exists i will create a new format key: None for db
        """
        descr = dd[elem].get("Descr", None)
        alias = dd[elem].get("Alias", None)
        speed = dd[elem].get("Speed", None)
        duplex = dd[elem].get("Duplex", None)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM