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

如何从python中的两个词典构造词典?,python,python-2.7,Python,Python 2.7,假设我有一本字典: x = {"x1":1,"x2":2,"x3":3} y = {"y1":1,"y2":2,"y3":3} 我还有一本字典: x = {"x1":1,"x2":2,"x3":3} y = {"y1":1,"y2":2,"y3":3} 有没有什么好方法可以从前两本词典中构造出第三本词典: z = {"y1":1,"x2":2,"x1":1,"y2":2} 您可以对x使用copy,然后使用update添加y中的键和值: z = x.copy() z.update(y

假设我有一本字典:

x = {"x1":1,"x2":2,"x3":3}
y = {"y1":1,"y2":2,"y3":3}
我还有一本字典:

x = {"x1":1,"x2":2,"x3":3}
y = {"y1":1,"y2":2,"y3":3}
有没有什么好方法可以从前两本词典中构造出第三本词典:

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

您可以对
x
使用
copy
,然后使用
update
添加
y
中的键和值:

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

如果您想要完整的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
输出:

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
如果需要部分命令:

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}

试着这样做:

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}

x3
y3
发生了什么事?对不起,我可能解释得不太清楚。我不想把这两本字典全部加在一起,做成一本新的。我只需要第一个和第二个的一些键,然后创建一个新的dictionary@user2468276我已经用您想要的更新了我的答案。
x={**x,**y}
第一个解决方案将在python2中工作,但在python2中不工作python3@JpuntoMarcos您是对的(旧答案),您可以使用
z=dict(list(x.items())+list(y.items())
用于python3,但请记住它更昂贵。