python_test_07

  1. 字典a={“x”:1,“z”:3},
    b={“y”:2,“z”:4},
    请设计一个函My_Func(),
    当My_Func(a,b)时输出c={“x”:1,“y”:2,“z”:3},
    当My_Func(b,a)时输出c={“x”:1,“y”:2,“z”:4}

    import operator
    
    a = {"x": 1, "z": 3}
    b = {"y": 2, "z": 4}
    
    
    def my_func(a, b):
    
        # 方法1:
        a.update(b)
        c = sorted(a.items, key=operator.itemgetter(1))
        print(c)
    
        # 方法2:
        c = {}
        for k in a.keys():
            c.setdefault(k, a[k])
        b1 = list(b.keys())
        c.setdefault(b1[0], b[b1[0]])
        c = sorted(c.items(), key=operator.itemgetter(1))
        print(c)
        
        # 方法3:
        d1 = list(a.keys())
        d2 = list(a.values())
        e1 = list(b.keys())
        e2 = b[e1[0]]
        d1.append(e1[0])
        d2.append(e2)
        d1.sort()
        d2.sort()
        c = {}
        for i in range(len(d1)):
            c.setdefault(d1[i], d2[i])
        print(c)
    
    my_func(a, b)
    my_func(b, a)
    

猜你喜欢

转载自blog.csdn.net/weixin_44786482/article/details/88894958