我是Python初学者,字典对我来说很新颖

-3 投票
3 回答
513 浏览
提问于 2025-04-15 15:29

给定两个字典,d1 和 d2,咱们要创建一个新的字典,要求是:对于 d1 中的每一对 (a, b),如果在 d2 中有一对 (b, c),那么就把 (a, c) 这对添加到新的字典里。 那么,怎么来思考这个问题呢?

3 个回答

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'、'b'和'c',对应的值分别是'aaa@example.com'、'bbb@example.com'和'ccc@example.com'。简单来说,这个字典就像一个小表格,左边是名字,右边是邮箱地址。

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

当然,你可以用更简洁的方式来表达这个意思,但我觉得对于初学者来说,把事情说得清楚一点会更明白,也更有帮助。

撰写回答