2016-11-08 228 views
3

一个循环我有两个词典。一个有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。我知道如何循环这两个字典(他们曾经是列表)。但它需要很长的时间。这就是为什么他们现在是字典,我认为我可以用所有章节的一个循环来管理。但在我的脑海里,我总是回过头来看书和章节。任何想法都非常感谢!我将在文件中写入最终结果,所以如果它是嵌套字典或其他东西,它不是很重要。或者至少我是这么认为的。遍历两个字典Python中

+0

尝试将词典压缩在一起,然后循环播放结果。可能仍然很贵,但值得一试。事实上,它可能会通过发电机懒惰地行动,所以它实际上可能非常便宜。 – Carcigenicate

+1

你的第一个字典是一个字典列表:是一个错字? – brianpck

+0

@brianpck是的,对不起 – student

回答

2

如果你是开放使用其他包,那么你可能希望有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) 
+0

这是一个很大的帮助! 45秒而不是20小时。我感到震惊:)但我不知道为什么reset_index步骤是必要的 – student

+0

很高兴它的工作:),使用reset_index使它从行索引到列,因此可以稍后进行合并。也许有可能在行名称合并,但没有花太多的时间在文档刷新我对如何做到这一点:)内存。要进一步了解http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html和http://pandas.pydata.org/pandas-docs/stable/merging.html –

2

你总是可以遍历字典键,所用的相同的键出现在两个字典:

for chapter_id in dict1: 
    book_id = dict1[chapter_id] 
    chapter_info = dict2[chapter_id] 
1
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一个聪明的办法。