Splice dictonary to create list of tuples in Python
<p>So I have these two dictonaries, where the key is a year (an integer), and the value a float. I want to combine these two, and as a result create a list of tuples, with the year, value1, value2. So like this:</p>

<p>Dictonary 1</p>

<pre><code> {2011: 1.0,
 2012: 2.0,
 2013: 3.0}
</code></pre>

<p>Dictonary 2</p>

<pre><code> {2011: 4.0,
 2012: 5.0,
 2013: 6.0}
</code></pre>

<p>Prefered result:</p>

<pre><code> [(2011, 1.0, 4.0),
 (2012, 2.0, 5.0),
 (2013, 3.0, 6.0)]
</code></pre>

<p>Is there an easy way of doing this? Thank for your help!</p>

<p>Here's few possible solutions:</p>

<pre><code>import timeit
import random

random.seed(1)


def f1(d1, d2):
    return [(k, d1[k], d2[k]) for k in list(set(d1.keys() + d1.keys()))]


def f2(d1, d2):
    return [(k, d1[k], d2[k]) for k in d1.viewkeys() &amp; d2]


def f3(d1, d2):
    return [(k, d1[k], d2[k]) for k in set().union(d1, d2)]

if __name__ == "__main__":
    d1_small = {2011: 1.0,
                2012: 2.0,
                2013: 3.0}

    d2_small = {2011: 4.0,
                2012: 5.0,
                2013: 6.0}

    K, I, N = 1000, 100000, 100
    d1_large = {i: random.randint(0, K) for i in range(I)}
    d2_large = {i: random.randint(0, K) for i in range(I)}

    # Small dataset
    print timeit.timeit('f1(d1_small,d2_small)', setup='from __main__ import f1, d1_small,d2_small', number=N)
    print timeit.timeit('f2(d1_small,d2_small)', setup='from __main__ import f2, d1_small,d2_small', number=N)
    print timeit.timeit('f3(d1_small,d2_small)', setup='from __main__ import f3, d1_small,d2_small', number=N)

    # Big dataset
    print timeit.timeit('f1(d1_large,d2_large)', setup='from __main__ import f1, d1_large,d2_large', number=N)
    print timeit.timeit('f2(d1_large,d2_large)', setup='from __main__ import f2, d1_large,d2_large', number=N)
    print timeit.timeit('f3(d1_large,d2_large)', setup='from __main__ import f3, d1_large,d2_large', number=N)
</code></pre>

<p>Results are:</p>

<pre><code>0.000144082492556
0.000120792445814
9.31601869678e-05
2.70233741278
2.74489385463
2.5809042933
</code></pre>

<p>Conclusion:</p>

<p>f3 is the winner here in terms of performance and f2 the one in terms of verbosity</p>

python python-2.7