2016-11-08 226 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一個聰明的辦法。