Python 3.x连接列表中不同字典值的字符串

时间:2017-03-27 10:00:44

标签: python string dictionary

我想连接一些字符串,这里是我目前的代码:

ad = {'documents':[{'id': '1', 'detectedLanguages': [{'name': 'english',
                                                     'iso6391': 'en',
                                                     'score': '1'},
                                                    {'name': 'french',
                                                     'iso6391': 'fr',
                                                     'score': '0.9'}]},
                  {'id': '2', 'detectedLanguages': [{'name': 'dutch',
                                                     'iso6391': 'hol',
                                                     'score': '1'},
                                                    {'name': 'russian',
                                                     'iso6391': 'rus',
                                                     'score': '0.9'}]}
                  ]
     }

langs = {}
for dct in ad['documents']:
    langs [str(dct['id'])] = (
        ','.join(x for detected_lang_dict in dct['detectedLanguages'] for x     in detected_lang_dict['iso6391'])
        )

print (langs)
#prints {'1': 'h,o,l,r,u,s'}

我希望结果如{' 1':' en,fr',' 2':' hol,rus' }

1 个答案:

答案 0 :(得分:2)

删除嵌套for以避免连接每个字符而不是整个字符串:

langs = {}
for dct in ad['documents']:
    langs[dct['id']] = ', '.join(d['iso6391'] for d in dct['detectedLanguages'])
print (langs)
# {'1': 'en, fr', '2': 'hol, rus'}

您不需要在dict键上调用字符串,它已经是一个字符串。

顺便说一下,您可以使用词典理解

langs = {dct['id']: ', '.join(d['iso6391'] for d in dct['detectedLanguages']) 
                                           for dct in ad['documents']}