splice dictonary在Python中创建元组列表

时间:2016-09-23 10:24:57

标签: python python-2.7

所以我有这两个dictonaries,其中键是一年(整数),值是浮点数。我想结合这两个,结果创建一个元组列表,其中year,value1,value2。像这样:

Dictonary 1

 {2011: 1.0,
 2012: 2.0,
 2013: 3.0}

Dictonary 2

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

首选结果:

 [(2011, 1.0, 4.0),
 (2012, 2.0, 5.0),
 (2013, 3.0, 6.0)]

有一种简单的方法吗?谢谢你的帮助!

2 个答案:

答案 0 :(得分:4)

以下是几种可能的解决方案:

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() & 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)

结果是:

0.000144082492556
0.000120792445814
9.31601869678e-05
2.70233741278
2.74489385463
2.5809042933

结论:

f3在性能方面是赢家,f2在详细程度方面是胜利者

答案 1 :(得分:2)

如果两个词典都具有相同的键:

[(k, dict1[k], dict2[k]) for k in dict1.keys()]

示例:

In[33]: dict1 =  {2011: 1.0,
 2012: 2.0,
 2013: 3.0}
In[34]: dict2 =  {2011: 4.0,
 2012: 5.0,
 2013: 6.0}
In[35]: [(k, dict1[k], dict2[k]) for k in dict1.keys()]
Out[35]: [(2011, 1.0, 4.0), (2012, 2.0, 5.0), (2013, 3.0, 6.0)]