How to construct a dictionary from two dictionaries in python?

This question already has an answer here:

  • How to merge two dictionaries in a single expression? 48 answers
  • Union of dict objects in Python [duplicate] 4 answers

  • If you want the whole 2 dicts:

    x = {"x1":1,"x2":2,"x3":3}
    y = {"y1":1,"y2":2,"y3":3}
    
    
    z = dict(x.items() + y.items())
    print z
    

    Output:

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

    If you want the partial dict:

    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
    

    Output

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

    你可以使用copy for x然后update来从y添加键和值:

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

    尝试这样的事情:

    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}
    
    链接地址: http://www.djcxy.com/p/17560.html

    上一篇: 字典python的联合

    下一篇: 如何从Python中的两个字典构造一个字典?