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

本问题已经有最佳答案,请猛点这里访问。

假设我有一本字典:

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

我还有一本字典:

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

有没有一种简洁的方法可以将前两本词典中的第三本词典压缩成:

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


如果你想要整两句话:

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


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

输出:

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

如果你想要部分dict:

1
2
3
4
5
6
7
8
9
10
11
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

输出

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


你可以对x使用copy,然后update来添加来自y的键和值:

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


试着这样做:

1
2
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}