我是一个python初学者,字典是新的

问题描述:

给定的字典,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

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

当然,您可以更简洁地表达这一点,但我认为,对于初学者来说,拼写出来的内容更清晰,更具启发性。

我同意亚历克斯在作为新手拼写事情的需要,并在稍后转向更简洁/抽象/危险的构造。

为了记录,我在这里列出了一个列表理解版本,因为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

#!/usr/local/bin/python3.1 
b = { 'aaa' : '[email protected]', 
     'bbb' : '[email protected]', 
     'ccc' : '[email protected]' 
    } 
a = {'a':'aaa', 'b':'bbb', 'c':'ccc'} 
c = {}  

for x in a.keys(): 
    if a[x] in b: 
     c[x] = b[a[x]] 

print(c) 

输出: { '一个': '[email protected]', 'c' 的:'[email protected]','b':'[email protected]'}