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

时间:2009-10-29 04:26:35

标签: python

给定字典d1和d2,创建一个具有以下属性的新字典:对于d1中的每个条目(a,b),如果d2中有条目(b,c),则条目(a,c) )应该添加到新词典中。 如何考虑解决方案?

3 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:4)

我同意Alex的观点,需要拼写新手,并在以后转向更简洁/抽象/危险的结构。

为了记录我在这里放置了一个列表理解版本,因为Paul似乎没有用。

>>> 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]])

答案 2 :(得分:0)

#!/usr/local/bin/python3.1
b = {   'aaa' : 'aaa@example.com',
        'bbb' : 'bbb@example.com',
        'ccc' : 'ccc@example.com'
    }
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)

输出: {'a':'aaa @ example.com','c':'ccc @ example.com','b':'bbb @ example.com'}