2009-10-29 58 views
-3

給定的字典,d1和d2,創建一個新的字典具有以下屬性:對於d1中的每個條目(a,b),如果有條目(b,c)在d2中,則應將條目(a,c)添加到新字典中。 如何看待解決方案?我是一個python初學者,字典是新的

+1

如果這是一個家庭作業問題,請標記爲這樣。 – 2009-10-29 04:28:12

+0

請不要發佈作業問題。只發布您的嘗試並詢問您不明白的具體問題。 – hasen 2009-10-29 07:52:34

回答

6
def transitive_dict_join(d1, d2): 
    result = dict() 
    for a, b in d1.iteritems(): 
    if b in d2: 
     result[a] = d2[b] 
    return result 

當然,您可以更簡潔地表達這一點,但我認爲,對於初學者來說,拼寫出來的內容更清晰,更具啓發性。

4

我同意亞歷克斯在作爲新手拼寫事情的需要,並在稍後轉向更簡潔/抽象/危險的構造。

爲了記錄,我在這裏列出了一個列表理解版本,因爲Paul's似乎並不工作。

>>> d1 = {'a':'alpha', 'b':'bravo', 'c':'charlie', 'd':'delta'} 
>>> d2 = {'alpha':'male', 'delta':'faucet', 'echo':'in the valley'} 
>>> d3 = dict([(x, d2[d1[x]]) for x in d1**.keys() **if d2.has_key(d1[x])]) #.keys() is optional, cf notes 
>>> d3 
{'a': 'male', 'd': 'faucet'} 

簡而言之,用 「d3 =」 的路線表示如下:

 
    d3 is a new dict object made from 
     all the pairs 
      made of x, the key of d1 and d2[d1[x]] 
       (above are respectively the "a"s and the "c"s in the problem) 
      where x is taken from all the keys of d1 (the "a"s in the problem) 
      if d2 has indeed a key equal to d1[x] 
       (above condition avoids the key errors when getting d2[d1[x]]) 
+0

是的,我沒有測試它。你的確做到了這一點。 – 2009-10-29 05:02:28

+0

有沒有讓你使用.keys()的原因?它與下面的不同: 'd3 = dict([(x,d2 [d1 [x]])對於d1中的x,如果d1 [x]在d2])'? – 2009-10-29 10:42:47

+0

@Andrea沒有什麼特別的理由,只是溫和地嘗試讓新手聽衆表達得更加明確(參見Alex'明智地接受這一點)。但是,你說得對'd1中的x代表'是枚舉d1的鍵的習慣方式。 – mjv 2009-10-29 12:34:38