[英]Filling a 'list' of dictionaries of key-values from 'list' of data
我在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]))]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.