【问题标题】:Python- Get information from matching keys in two dictionaries?Python-从两个字典中的匹配键中获取信息?
【发布时间】:2017-04-22 16:22:22
【问题描述】:

我正在尝试构建一个结合两个字典的函数。这应该很容易,但有一个问题。

给定两个字典:

info_format_dict={ name: (id, type1, type2, generation, legendary), 
'Bulbasaur': (1, 'Grass', 'Poison', 1, False), 'Charmander': (4, 
'Fire', None, 1, False)}

stats_format_dict={ id: (hp, attack, defense, speed),1: (45, 49, 49, 
45)}

只有在两个字典中都找到 ID 号时,我才必须合并字典。所以在这个例子中,从 info_format_dict 'Bulbasaur' 的 id 为 1,在 stats_format_dict 中,1 是 id 号。他们匹配。然后我必须按以下格式将该项目添加到新字典中:

new_dict={"Bulbasaur": (1, "Grass", "Poison", 45, 49, 49, 45, 1, 
False)}

任何其他没有匹配的都将被丢弃。我创建的函数将字典放入列表中进行比较,但是一旦找到匹配项,我就会陷入如何进行实际组合的问题。我如何进行实际的组合,我的检查是否正确?

这是我的代码:

def combine_databases(info_format_dict,stats_format_dict):
    statskeyslist=[]
    idnums=[]   
    for key,values in info_format_dict.items():
        idnum=values[0]
        idnums.append(idnums)

    for keys in stats_format_dict:
        stats_key=keys
        statskeyslist.append(keys) 

    for item in statskeyslist:
        if item in idums:
        #combine them into a dictionary

建议?解决方案?

【问题讨论】:

    标签: python-3.x dictionary for-loop


    【解决方案1】:

    您的内部循环内部都有两个键。 (鉴于您在上面创建了它们,您应该能够推理为什么!)您为什么不尝试从每个字典中获取值并尝试组合它们呢?

    v1 = info_format_dict[item]
    v2 = stats_format_dict[item]
    

    你应该能够保证这里不会抛出异常。 (为什么?)

    然后您需要将它们粘贴到其他字典中才能返回。

    【讨论】:

    • 按什么顺序?在按键之前还是之后?
    • 嗯,有什么意义呢?您了解将项目添加到 dict 的工作原理吗?尝试两者,看看会发生什么。
    猜你喜欢
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 2018-12-14
    • 2020-03-31
    • 1970-01-01
    相关资源
    最近更新 更多