繁体   English   中英

更改python词典的格式

[英]change format of python dictionary

我有以下格式的python字典:

{('first', 'negative'): 57, ('first', 'neutral'): 366, ('first', 'positive'): 249, ('second', 'negative'): 72, ('second', 'neutral'): 158, ('second', 'positive'): 99, ('third', 'negative'): 156, ('third', 'neutral'): 348, ('third', 'positive'): 270}

我想将其转换为:

{'first': [{'sentiment':'negative', 'value': 57}, {'sentiment': 'neutral', 'value': 366}, {'sentiment': 'positive', 'value': 249}], 'second': [{'sentiment':'negative', 'value': 72}, {'sentiment': 'neutral', 'value': 158}, {'sentiment': 'positive', 'value': 99}], 'third': [{'sentiment':'negative', 'value': 156}, {'sentiment': 'neutral', 'value': 348}, {'sentiment': 'positive', 'value': 270}]}

提前致谢

这应该有所帮助。

o = {('first', 'negative'): 57, ('first', 'neutral'): 366, ('first', 'positive'): 249, ('second', 'negative'): 72, ('second', 'neutral'): 158, ('second', 'positive'): 99, ('third', 'negative'): 156, ('third', 'neutral'): 348, ('third', 'positive'): 270}
d = {}
for k,v in o.items():  #Iterate over your dict
    if k[0] not in d:
        d[k[0]] = [{"sentiment":k[1] , "value": v}]
    else:
        d[k[0]].append({"sentiment":k[1] , "value": v})
print d

输出:

{'second': [{'value': 72, 'sentiment': 'negative'}, {'value': 99, 'sentiment': 'positive'}, {'value': 158, 'sentiment': 'neutral'}], 'third': [{'value': 156, 'sentiment': 'negative'}, {'value': 348, 'sentiment': 'neutral'}, {'value': 270, 'sentiment': 'positive'}], 'first': [{'value': 57, 'sentiment': 'negative'}, {'value': 366, 'sentiment': 'neutral'}, {'value': 249, 'sentiment': 'positive'}]}
from collections import defaultdict

out = defaultdict(list)

for (label, sentiment), value in input_dict.items():
       out[label].append(dict(sentiment=sentiment, value=value))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM