简体   繁体   中英

Dict of string key-value pairs

I have a list of countries and capitals that I would like to convert into a dict. Here, both key and value are strings.

from countrygroups import EUROPEAN_UNION
from countryinfo import CountryInfo

countries = EUROPEAN_UNION.names
print(countries)

['Austria', 'Belgium', 'Bulgaria', 'Croatia', 'Cyprus', 'Czechia', 'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'Ireland', 'Italy', 'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Netherlands', 'Poland', 'Portugal', 'Romania', 'Slovakia', 'Slovenia', 'Spain', 'Sweden', 'United Kingdom']

The following code will print country:capital for each country but how does one construct a dict from these key-value pairs in Python3?

for country in countries:
    if country == 'Czechia':
        country = 'Czech Republic'
    cinfo = CountryInfo(country)
    print(country  + ' : ' + cinfo.capital())


Austria : Vienna
Belgium : Brussels
Bulgaria : Sofia
Croatia : Zagreb
Cyprus : Nicosia
...

Replace you for loop with this:

countries_dict = {}
for country in countries:
    if country == 'Czechia':
        country = 'Czech Republic'

    cinfo = CountryInfo(country)
    countries_dict[country] = cinfo.capital()

    print(country  + ' : ' + cinfo.capital())

You should fix the erroneous data (country name) separately. Then use a dictionary comprehension to build the dictionary:

countries[countries.index('Czechia')]  = 'Czech Republic' # fix input data
dictionary = { country:CountryInfo(country).capital() for country in countries }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM