简体   繁体   中英

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

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]} .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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