我有一个"庞大"的国家列表以及与每个国家相关的数据,作为python中的列表。我需要将数据映射到每个列表。因此,经过一些谷歌搜索,已经为此目的使用python中的字典。也就是说,每个国家/地区的每个词典都会生成一个词典列表。然后用大写、语言和人口等数据(键(及其相应的值填充这些字典。最终,我应该将它们全部作为numpy数组,因为我需要绘制例如,国家及其人口的图形。
我只是一个初学者,所以请随时提出更好的方法。这是我开始的(将我的字典减少到只有 4 个(,不知何故走到了死胡同。
#!/usr/bin/python
#
#Dictionary example
#
import numpy as np
if __name__ == '__main__':
country_names = [ 'Germany', 'Italy', 'Netherlands', 'France'] #list of countries
capital_list =['Berlin', 'Rome', 'Amsterdam', 'Paris']#list of capitals to be mapped to countries
population_list= ['3.5','2.1', '0.3', '2.8'] #list of population of induvidual countries, all figures in Million
language_list=['German','Italian','Dutch','French'] #list of languages to be mapped to countries
#dict1={"CAPITAL":xxx, "POPULATION":yyy, "LANGUAGE": zzz} ##map these data as key value pairs for each country(where each country is a dictionary)
dictionary_list ={ "CAPITAL": i, "POPULATION":i, "LANGUAGE": i for i in country_names}
#dictionary_list ={ i: [] for i in country_names}
for i in range(len(country_names)):
dictionary_list['CAPITAL'] = capital_list[i]
dictionary_list['POPULATION'] = population_list[i]
dictionary_list['LANGUAGE'] = language_list[i]
print dictionary_list
#for value in dict.itervalues(): ...
#for key, value in dict.iteritems():
#numpy array of dictionary
我的问题是我不明白如何以交互方式创建字典并用它们的值迭代填充键。唯一固定的指标是关键(目前只有3个是人口,语言和资本(。
您可以使用
zip
前任:
country_names = [ 'Germany', 'Italy', 'Netherlands', 'France'] #list of countries
capital_list =['Berlin', 'Rome', 'Amsterdam', 'Paris']#list of capitals to be mapped to countries
population_list= ['3.5','2.1', '0.3', '2.8'] #list of population of induvidual countries, all figures in Million
language_list=['German','Italian','Dutch','French'] #list of languages to be mapped to countries
dictionary_list = [ {"COUNTRY": country, "CAPITAL": capital, "POPULATION":population, "LANGUAGE": lang} for country, capital, population, lang in zip(country_names, capital_list, population_list, language_list)]
print(dictionary_list)
或
keys = ["COUNTRY", "CAPITAL", "POPULATION", "LANGUAGE"]
dictionary_list = [ dict(zip(keys,data)) for data in zip(country_names, capital_list, population_list, language_list)]
print(dictionary_list)
输出:
[{'CAPITAL': 'Berlin',
'COUNTRY': 'Germany',
'LANGUAGE': 'German',
'POPULATION': '3.5'},
{'CAPITAL': 'Rome',
'COUNTRY': 'Italy',
'LANGUAGE': 'Italian',
'POPULATION': '2.1'},
{'CAPITAL': 'Amsterdam',
'COUNTRY': 'Netherlands',
'LANGUAGE': 'Dutch',
'POPULATION': '0.3'},
{'CAPITAL': 'Paris',
'COUNTRY': 'France',
'LANGUAGE': 'French',
'POPULATION': '2.8'}]
你想要 :
headers = ['name' , 'capital' , 'language']
arrs = [country_names , population_list, language_list]
dicts = [ { name: arr[x] for name, arr in zip(headers, arrs )} for x in range(len(country_names [0]))]