ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python] dict 타입끼리 더하기
    언어/파이썬 & 장고 2016. 10. 5. 18:03


    a = {'a':1,'b':2,'c':3}
    b= {'d':4,'e':5,'c':4444}
     
    # 1. 덧셈
    z=a+b
    print(z)
    # dict끼리는 +를 지원하지 않아 에러
     
    # 2.
    z = {**a, **b}
    # python 3.5부터 지원 이하버젼 x
     
    # 3.
    z = a.copy()
    z.update(b)
     
    # dict끼리 덧셈이 가능하고 동일한 키가 존재하면 키들 간에 가장 큰 값으로 대체됨
     
    # 3.1 응용편
    def merge(*dict_args):
        print(dict_args)
        result = {}
        for dictionary in dict_args:
            result.update(dictionary)
        return result
    
    
    a = {'a':1,'b':2,'c':3}
    b= {'d':4,'e':5,'c':4444}
    c={....}
    d={....}
    z = merge(a,b,c,d)
     
    # *args로 받기 때문에 넘겨받은 dict를 전부 더해서 반환
     
     
    # 4. from collections import Counter
    from collections import Counter
    a = Counter({'a':1,'b':2,'c':3})
    b= Counter({'d':4,'e':5,'c':4444})
    
    z = a+b
    
    
    # 3. 과 같이 동일한 키값에 대해 정책이 적용되면서 dict끼리 덧셈성공



    참조: http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression

    댓글