如何从python中的两个词典构造一个字典?

时间:2013-12-04 11:41:25

标签: python python-2.7

假设我有一本字典:

x = {"x1":1,"x2":2,"x3":3}

我还有另一本字典:

y = {"y1":1,"y2":2,"y3":3}

有没有任何巧妙的方法来构建前两个字典中的第三个字典:

z = {"y1":1,"x2":2,"x1":1,"y2":2}  

3 个答案:

答案 0 :(得分:6)

如果你想要整个2个词组:

x = {"x1":1,"x2":2,"x3":3}
y = {"y1":1,"y2":2,"y3":3}


z = dict(x.items() + y.items())
print z

<强>输出:

{'y2': 2, 'y1': 1, 'x2': 2, 'x3': 3, 'y3': 3, 'x1': 1}

如果你想要部分字典:

x = {"x1":1,"x2":2,"x3":3}
y = {"y1":1,"y2":2,"y3":3}

keysList = ["x2", "x1", "y1", "y2"]
z = {}

for key, value in dict(x.items() + y.items()).iteritems():
    if key in keysList:
        z.update({key: value})

print z

<强>输出

{'y1': 1, 'x2': 2, 'x1': 1, 'y2': 2}

答案 1 :(得分:5)

您可以copy使用x,然后update使用y添加密钥和值:

z = x.copy()
z.update(y)

答案 2 :(得分:0)

尝试这样的事情:

dict([(key, d[key]) for d in [x,y] for key in d.keys() if key not in ['x3', 'y3']])
{'x2': 2, 'y1': 1, 'x1': 1, 'y2': 2}