从字典中提取元素

时间:2017-03-06 21:28:47

标签: python dictionary

我正在使用IBM沃森音调分析器获得如下输出:

x= {
    u'document_tone': {
        u'tone_categories': [
            {
                u'category_id': u'social_tone',
                u'category_name': u'Social Tone',
                u'tones': [
                    {
                        u'score': 0.284871,
                        u'tone_id': u'openness_big5',
                        u'tone_name': u'Openness'},
                    {
                        u'score': 0.274523,
                        u'tone_id': u'conscientiousness_big5',
                        u'tone_name': u'Conscientiousness'},
                    {
                        u'score': 0.545545,
                        u'tone_id': u'extraversion_big5',
                        u'tone_name': u'Extraversion'},
                    {
                        u'score': 0.599657,
                        u'tone_id': u'agreeableness_big5',
                        u'tone_name': u'Agreeableness'},
                    {
                        u'score': 0.348563,
                        u'tone_id': u'emotional_range_big5',
                        u'tone_name': u'Emotional Range'}
                ]
            }
        ]
    }
}

如果我只想从中提取4个值,我该怎么做?

我想要像Openness = 0.284871,Emotional Range = 0.348562

这样的变量

2 个答案:

答案 0 :(得分:2)

tones = x['document_tone']['tone_categories'][0]['tones']
kv = {tone['tone_name']: tone['score'] for tone in tones}
print kv['Openness']
print kv['Emotional Range']

答案 1 :(得分:1)

试试这个:

>>> {tone['tone_name']:tone['score']  for cat in x['document_tone']['tone_categories'] for tone in cat['tones']}
{u'Emotional Range': 0.348563, u'Openness': 0.284871, u'Extraversion': 0.545545, u'Agreeableness': 0.599657, u'Conscientiousness': 0.274523}