파이썬에서 딕셔너리 값을 비교해서 통합하고 싶습니다.

조회수 1945회

감성 분석 과제를 수행하는 도중, 다음과 같이 개별 키값과 밸류값을 저장한 리스트-딕셔너리를 생성했습니다.

tempDict = [{'Entity': '아니', 'Feature': 'GEN', 'Nagative': 1, 'SNagative': 1},
{'Entity': '아니', 'Feature': 'GEN', 'Nagative': 1, 'SNagative': 1},
{'Entity': '로', 'Feature': '사진', 'Positive': 1, 'SNagative': 1},
{'Entity': '로', 'Feature': '사진', 'Negative': 1}
{'Entity': '로', 'Feature': '카메라', 'Negative': 1}]

위와 같은 상태에서, 동일한 'Entity/Feature'값을 가지는 요소들의 극성값들을 통합하여 다음과 같은 형태로 만들고자 합니다.

newDict = [{'Entity': '아니', 'Feature': 'GEN', 'Nagative': 2, 'SNagative': 2},
{'Entity': '로', 'Feature': '사진', 'Positive': 1, 'SNagative': 1, 'Negative': 1}]
{'Entity': '로', 'Feature': '카메라', 'Negative': 1}]

딕셔너리에 대한 이해도가 낮아 해결하지 못하고 있습니다.. 방법을 알려주시면 감사하겠습니다.

  • (•́ ✖ •̀)
    알 수 없는 사용자

2 답변

  • >>> tempDict = [{'Entity': '아니', 'Feature': 'GEN', 'Nagative': 1, 'SNagative': 1},
    {'Entity': '아니', 'Feature': 'GEN', 'Nagative': 1, 'SNagative': 1},
    {'Entity': '로', 'Feature': '사진', 'Positive': 1, 'SNagative': 1},
    {'Entity': '로', 'Feature': '사진', 'Negative': 1},
    {'Entity': '로', 'Feature': '카메라', 'Negative': 1}]
    >>> import pandas as pd
    
    >>> df = pd.DataFrame(tempDict)
    >>> df
      Entity Feature  Nagative  SNagative  Positive  Negative
    0     아니     GEN       1.0        1.0       NaN       NaN
    1     아니     GEN       1.0        1.0       NaN       NaN
    2      로      사진       NaN        1.0       1.0       NaN
    3      로      사진       NaN        NaN       NaN       1.0
    4      로     카메라       NaN        NaN       NaN       1.0
    >>> df = df.fillna(0)
    >>> df
      Entity Feature  Nagative  SNagative  Positive  Negative
    0     아니     GEN       1.0        1.0       0.0       0.0
    1     아니     GEN       1.0        1.0       0.0       0.0
    2      로      사진       0.0        1.0       1.0       0.0
    3      로      사진       0.0        0.0       0.0       1.0
    4      로     카메라       0.0        0.0       0.0       1.0
    
    >>> df1 = df.groupby(['Entity', 'Feature'], as_index=False).sum()
    >>> df1
      Entity Feature  Nagative  SNagative  Positive  Negative
    0      로      사진       0.0        1.0       1.0       1.0
    1      로     카메라       0.0        0.0       0.0       1.0
    2     아니     GEN       2.0        2.0       0.0       0.0
    

    pandas dataframe 으로 바꾸어 놓고, groupby 를 사용하는 방법입니다.

    • 정확히 제가 원하던 것이었습니다. 도움 주셔서 매우 감사드립니다. 알 수 없는 사용자 2019.12.2 23:55
  • 기본모듈만으로 작성해봤습니다.

    간단하게 될 것 같아서 시작했는데 생각보다 고려할 것이 있네요. 이렇게 길어지면 comprehension 보다 별도의 함수로 작성하는 편이 낫습니다.

    tempDict = [{'Entity': '아니', 'Feature': 'GEN', 'Nagative': 1, 'SNagative': 1},
    {'Entity': '아니', 'Feature': 'GEN', 'Nagative': 1, 'SNagative': 1},
    {'Entity': '로', 'Feature': '사진', 'Positive': 1, 'SNagative': 1},
    {'Entity': '로', 'Feature': '사진', 'Negative': 1},
    {'Entity': '로', 'Feature': '카메라', 'Negative': 1}]
    
    import itertools as it
    from collections import Counter
    from functools import reduce
    
    tempdict_grouped = {(('Entity',key[0]), ('Feature', key[1])): 
                            tuple((reduce(lambda x, y: x + y, [Counter({_k: _v for _k, _v in di.items() if _k not in ['Entity', 'Feature']}) for di in group])).items()) 
                                for key, group in it.groupby(tempDict, lambda e:(e['Entity'], e['Feature']))}
    
    for k, v in tempdict_grouped.items():
        print({**dict(k), **dict(v)})
    {'Entity': '아니', 'Feature': 'GEN', 'Nagative': 2, 'SNagative': 2}
    {'Entity': '로', 'Feature': '사진', 'Positive': 1, 'SNagative': 1, 'Negative': 1}
    {'Entity': '로', 'Feature': '카메라', 'Negative': 1}
    
    
    • 다시 확인한 결과, 잘 작동하는 것으로 확인됩니다. 감사합니다! 알 수 없는 사용자 2019.12.6 00:38
    • 아 import itertools as it 가 빠졌네요 정영훈 2019.12.6 01:15

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)