python - 遍历两个字典

标签 python

我有两本词典:

dict_1 = {'H1':[0,1,3,2],
          'H2':[5,4,2,1,5],
          'H3':[1,2,5]}

dict_2 = {'H1':[[1,4,3,2],
                [6,5,3,2],
                [1,4,3,2]],
          'H2':[[0,0,1,6,3],
                [2,1,4,2,1],
                [5,1,2,5,3]],
          'H3':[[2,3,4],
                [2,1,4],
                [0,1,2]]}

我正在尝试迭代 dict_1 中键值中的项目,并检查这些项目中是否有任何项目位于 dict_2 中相应键值中的任何项目中。然后打印该值以及在 dict_2 的键中找到该值的索引。

例如,由于 dict_1 的键“H1”的列表中的 0 在 dict 2 的键“H1”的任何列表中都找不到,因此不会打印任何内容。现在如果我们检查 1,那么

1, 'H1', 0, # because there is a one in the first list of 'H1' of dict_2
1, 'H1', 2, # because there is a one in the 3rd list of 'H1' of dict_2

此处 1 对应于已检查的项目,'H1' 对应于已检查的键,0 >2 表示 1 在 dict_2 中的哪个列表中找到

这就是我所拥有的:

for i in range(3):
    for k,v in dict_1.items():
        for x,y in dict_2.items():
            if k == x:
                for j in v:
                    if j in y[i]:
                        print j,x,i

但我想知道这是否能解决所有问题,或者是否会打印重复的项目?

最佳答案

这应该有效:

for key, d1_list in dict_1.iteritems():
    for element in d1_list:
        for ind, d2_list in enumerate(dict_2[key]):
            if element in d2_list:
                print element, key, ind

迭代所有键、列表和 d1。然后遍历 d1_list 中的元素,最后检查是否是 dict_2 中与相同键对应的任何列表。

关于python - 遍历两个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35212716/

相关文章:

python - pandas 数据帧上的多重处理。基于输入大小的令人困惑的行为

python - 值错误 : Input arrays should have the same number of samples as target arrays. 找到 166 个输入样本和 4 个目标样本

python - 使用 JSON 数据更新 mpld3 图

python - 如何在带有 i18n 的 mako 渲染模板中使用 _?

Python 查询处理和 bool 搜索

python - 如何将类中的函数应用到 Pandas Dataframe 中

python - 内部 Keras 模型中的多个嵌入层问题

python - 如何以与setuptools相同的方式在bitbake配方中使用setuptools3存储pyc文件?

python - 获取数组中元素的频率计数

python - 有什么方法可以检测 python 中输入错误的 url 吗?