Given dictionaries, d1 and d2, create a new dictionary with the following property: for each entry (a, b) in d1, if there is an entry (b, c) in d2, then the entry (a, c) should be added to the new dictionary. How to think of the 开发者_如何学运维solution?
def transitive_dict_join(d1, d2):
result = dict()
for a, b in d1.iteritems():
if b in d2:
result[a] = d2[b]
return result
You can express this more concisely, of course, but I think that, for a beginner, spelling things out is clearer and more instructive.
I agree with Alex, on the need of spelling things out as a novice, and to move to more concise/abstract/dangerous constructs later on.
For the record I'm placing here a list comprehension version as Paul's doesn't seem to work.
>>> 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'}
In a nutshell, the line with "d3 =
" says the following:
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]])
#!/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)
OutPut: {'a': 'aaa@example.com', 'c': 'ccc@example.com', 'b': 'bbb@example.com'}
精彩评论