gpt4 book ai didi

Python 列表到带键的字典

转载 作者:太空宇宙 更新时间:2023-11-04 08:00:03 25 4
gpt4 key购买 nike

我有以下列表:

[['Andorra', '19165'], ['Algeria', '233724']]

每个子列表中的第一个值是 - country

每个子列表中的第二个值是 - population

我如何从这个列表中创建一个字典,它将 country 键和 population 键设置为子列表中的每个值。

我期待这样的结果:

{'Country': 'Andora', 'population': '19165'}, ....

最佳答案

关于:

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'}]

关于Python 列表到带键的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41722033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com