How to do an 'inner join' with dictionaries
Claudio Grondi
claudio.grondi at freenet.de
Mon Feb 27 09:07:31 EST 2006
cyborg4 at walla.co.il wrote:
> Let's say I have two dictionaries:
> dict1 is 1:23, 2:76, 4:56
> dict2 is 23:A, 76:B, 56:C
>
> How do I get a dictionary that is
> 1:A, 2:B, 4:C
>
Just copy/paste the following source code to a file and run it:
<code>
sourceCodeToExecute = """
dict1 = { 1:23, 2:76, 4:56 }
dict2 = { 23:'A', 76:'B', 56:'C' }
# How do I get a dictionary that is
dict3 = { 1:'A', 2:'B', 4:'C' }
dict4 = {}
for key in dict1.keys():
dict4[key] = dict2[dict1[key]]
#:for
print 'dict3 == dict4 is', dict3 == dict4
"""
print
print ' execution of following source code: '
print
print '"""',
print sourceCodeToExecute
print '"""'
print
print ' results in output of: '
print
exec(sourceCodeToExecute)
</code>
The core idea of an inner join:
dict2[dict1[key]]
Hope this helps inspite of the fact there is some more complicated code
involved, which I provided to show the beauty of Python from the point
of view of my own style of writing 'tutorial-like' code which explains
itself by its output.
Claudio
More information about the Python-list
mailing list