简体   繁体   English

从 2 个字典创建嵌套字典

[英]Creating a Nested Dictionary from 2 Dictionaries

I have 2 dictionaries that I created and need to now try to combine those.我有 2 个我创建的字典,现在需要尝试将它们组合起来。 I have searched for days now try to find something similar to this but the examples I see aren't quite doing what I am looking for and/or are not working for me and I don't know what I may be missing or if something is wrong with my dictionaries.我已经搜索了好几天,现在试图找到类似的东西,但我看到的例子并没有完全符合我的要求和/或不适合我,我不知道我可能会错过什么或是否有什么我的字典有问题。 Can I get some advice?我能得到一些建议吗?

Examples of the dics I have:我拥有的 dics 示例:

pro_go: {
    Q9Y7X7 : ['GO:0003674','GO:0005829'...],  
    'Q9Y819': ['GO:0008150','GO:0005794',...]...
}
go_def: {
    'GO:0010332': 'response to gamma radiation', 
    'GO:0010337': 'cellulose synthase', ...
}

What I need to continue on with my project:我需要继续我的项目:

pro_go_def: {
    Q9Y7X7: {
        'GO:xxxxxx': response, 
        'GO:xxxxxx': metabolism...
    }, 
    Q9Y819:{
        'GO:xxxxx': cell wall, 
        'GO:xxxxx': 'transporter activity',
    } ....
}

So I need a dictionary pro_go key, pro_go value=go_def key, go_def value所以我需要一个字典 pro_go key, pro_go value=go_def key, go_def value

I have to keep it basic and not use any other packages(?) like panda or collections that I seen in some of the examples.我必须保持基本并且不使用我在一些示例中看到的任何其他包(?),如 panda 或 collections。 And I'd love any explanations that you may give, I really want to understand whats going on and really am lost with Python at this point.我很喜欢你可能给出的任何解释,我真的很想了解发生了什么,并且在这一点上真的迷失了 Python。

Something like this?像这样的东西?

pro_go_def = {
    k: {elem: go_def[elem] for elem in v if elem in go_def}
    for k, v in pro_go.items()
}
from collections import ChainMap

dict1 = {'name': 'Jack', 'age':22} 
dict2 = {'gender':'male'}

dict_common = ChainMap(dict1,dict2)



 for i in dict_common.keys():
        print(i)

Result结果

gender name age性别名称年龄

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

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