当前位置:  开发笔记 > 编程语言 > 正文

Python列表与键的字典

如何解决《Python列表与键的字典》经验,为你挑选了1个好方法。



1> Willem Van O..:

关于什么:

result = {country:pop for country,pop in source}

source您的子列表列表在哪里.

或者在shell中:

>>> source = [['Andorra', '69165'], ['Algeria', '40375954'], ['Antigua and Barbuda', '92738'], ['Azerbaijan', '9868447'], ['Australia', '24309330'], ['Aruba', '104263'], ['Albania', '2903700'], ['American Samoa', '55602'], ['Afghanistan', '33369945'], ['Anguilla', '14763'], ['Austria', '8569633'], ['Armenia', '3026048'], ['Angola', '25830958'], ['Argentina', '43847277']]
>>> {country:pop for country,pop in source}
{'Andorra': '69165', 'Angola': '25830958', 'Austria': '8569633', 'Armenia': '3026048', 'Anguilla': '14763', 'American Samoa': '55602', 'Albania': '2903700', 'Australia': '24309330', 'Afghanistan': '33369945', 'Aruba': '104263', 'Azerbaijan': '9868447', 'Argentina': '43847277', 'Antigua and Barbuda': '92738', 'Algeria': '40375954'}
编辑

在重读你的问题后,我想你会寻找:

result = [{'country':country,'population':pop} for country,pop in source]

这给出了:

>>> source = [['Andorra', '69165'], ['Algeria', '40375954'], ['Antigua and Barbuda', '92738'], ['Azerbaijan', '9868447'], ['Australia', '24309330'], ['Aruba', '104263'], ['Albania', '2903700'], ['American Samoa', '55602'], ['Afghanistan', '33369945'], ['Anguilla', '14763'], ['Austria', '8569633'], ['Armenia', '3026048'], ['Angola', '25830958'], ['Argentina', '43847277']]
>>> [{'country':country,'population':pop} for country,pop in source]
[{'population': '69165', 'country': 'Andorra'}, {'population': '40375954', 'country': 'Algeria'}, {'population': '92738', 'country': 'Antigua and Barbuda'}, {'population': '9868447', 'country': 'Azerbaijan'}, {'population': '24309330', 'country': 'Australia'}, {'population': '104263', 'country': 'Aruba'}, {'population': '2903700', 'country': 'Albania'}, {'population': '55602', 'country': 'American Samoa'}, {'population': '33369945', 'country': 'Afghanistan'}, {'population': '14763', 'country': 'Anguilla'}, {'population': '8569633', 'country': 'Austria'}, {'population': '3026048', 'country': 'Armenia'}, {'population': '25830958', 'country': 'Angola'}, {'population': '43847277', 'country': 'Argentina'}]

推荐阅读
殉情放开那只小兔子
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有