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?
+6
A:
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.
Alex Martelli
2009-10-29 04:48:05
+4
A:
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]])
mjv
2009-10-29 04:59:26
Yeah, I didn't test it. Yours does do the trick.
Paul McMillan
2009-10-29 05:02:28
Is there a reason that makes you use .keys()? Is it different from: `d3 = dict([(x, d2[d1[x]]) for x in d1 if d1[x] in d2])`?
Andrea Ambu
2009-10-29 10:42:47
@Andrea No particular reason but a mild attempt at making the expression more explicit for a novice audience (cf Alex' wise take on this). But, you are right `x for x in d1` is the idiomatic way of enumerating the keys of d1.
mjv
2009-10-29 12:34:38
A:
#!/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)
OutPut: {'a': '[email protected]', 'c': '[email protected]', 'b': '[email protected]'}
Danny Shih
2009-10-29 06:46:11