我有一个这种格式的python字典:
main section {
float:left;
width: 50%;
text-align: justify;
padding: 5px 10px;
box-sizing: border-box;
}
我想将其转换为:
{('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}
提前致谢
答案 0 :(得分:0)
这应该有所帮助。
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'}]}
答案 1 :(得分:0)
from collections import defaultdict
out = defaultdict(list)
for (label, sentiment), value in input_dict.items():
out[label].append(dict(sentiment=sentiment, value=value))