【问题标题】:Iterate over two dictionaries in one loop in python在python的一个循环中迭代两个字典
【发布时间】:2016-11-08 14:42:41
【问题描述】:

我有两本词典。一个有 chapter_id 和 book_id:{99: 7358, 852: 7358, 456: 7358}。这里仅以一本书为例,但还有很多。还有一个相同的chapter_id和一些信息:{99: [John Smith, 20, 5], 852: [Clair White, 15, 10], 456: [Daniel Dylan, 25, 10]}。章节 ID 在所有书籍中都是唯一的。我必须以每本书从它包含的所有章节中获取信息的方式来组合它。像{7358:[[99,852,456],[John Smith, Claire White, Daniel Dylan],[20,15,25],[5,10,10]]} 这样的东西。我也有一个带有字典的文件,其中每本书都有它所有章节的 ID。我知道如何通过遍历两个字典(它们曾经是列表)来做到这一点。但这需要很长时间。这就是为什么它们现在是字典,我想我可以只用一个循环遍历所有章节。但在我的脑海中,我总是回到循环阅读书籍和章节。任何想法都非常感谢!最后的结果我会写在文件里,所以是嵌套字典还是别的什么的都不是很重要。或者至少我是这么认为的。

【问题讨论】:

  • 尝试将字典压缩在一起,然后遍历结果。可能仍然很贵,但值得一试。实际上,它可能会通过生成器进行惰性操作,因此它实际上可能非常便宜。
  • 你的第一个 dict 是一个 dicts 列表:这是一个错字吗?
  • @brianpck 是的,对不起

标签: python loops dictionary


【解决方案1】:

如果您愿意使用其他软件包,那么您可能想看看pandas,它可以让您轻松快速地做很多事情。这是基于您提供的数据的示例...

import pandas as pd
d1 = {99: 7358, 852: 7358, 456: 7358}
df1 = pd.DataFrame.from_dict(d1, "index")
df1.reset_index(inplace=True)

d2 = {99: ["John Smith", 20, 5], 852: ["Clair White", 15, 10], 456: ["Daniel Dylan", 25, 10]}
df2 = pd.DataFrame.from_dict(d2, "index")
df2.reset_index(inplace=True)

df = df1.merge(df2, left_on="index", right_on="index")
df.columns = ["a", "b", "c", "d", "e"]

# all data for 7358 (ie subsetting)
df[df.b == 7358]
# all names as a list
list(df[df.b == 7358].c)

【讨论】:

【解决方案2】:

您总是可以遍历字典键,因为两个字典中都出现了相同的键:

for chapter_id in dict1:
    book_id = dict1[chapter_id]
    chapter_info = dict2[chapter_id]

【讨论】:

    【解决方案3】:
    from collections import defaultdict
    
    def append_all(l, a):
        if len(l) != len(a):
            raise ValueError
        for i in range(len(l)):
            l[i].append(a[i])
    
    
    final_dict = defaultdict(lambda: [[],[],[],[]])
    for chapter, book in d1.items():
        final_dict[book][0].append(chapter)
        append_all(final_dict[book][1:], d2[chapter])
    

    您只需要遍历章节。您可以用显式附加替换 append_all 函数,但这样做似乎很难看。我很惊讶没有办法解决这个问题,但可能只是我错过了在这里使用zip 的聪明方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      • 2021-02-07
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多