简体   繁体   中英

Combining 3 Lists into a lists of dictionaries in python

I just started to learn Python, and a completely a noob at it. So what I want to do is merge 3 lists into a lists of dictionary

country= ["Japan", "Malaysia", "Philippine", "Thailand"]
capital = ["Tokyo", "Kuala Lumpur", "Manila", "Bangkok"]
currency = ["Yen", "Ringgit", "Peso", "Bath"]

into a list in this format:

data = [{"country":"Japan", "capital":"Tokyo", "currency":"Yen"}, {"country":"Malaysia", "capital":"Kuala Lumpur", "currency":"Ringgit"}, {"country":"Philippine", "capital":"Manila", "currency":"Peso"},{"country":"Thailand", "capital":"Bangkok", "currency":"Bath"}]

And then print the new list in this format:

Capital of Japan is Tokyo, and the currency is Yen.
Capital of Malaysia is Kuala Lumpur, and the currency is Ringgit.
Capital of Philippine is Manila, and the currency is Peso.
Capital of Thailand is Bangkok, and the currency is Bath.

A simple list comprehension with zip is all you need:

data = [{'country':coun, 'capital': cap, 'currency': curr} for coun, cap, curr in zip(country, capital, currency)]

You can then iterate through data and print as so:

for dictionary in data:
    print("Capital of {0} is {1} and currency is {2}".format(dictionary['country'],dictionary['capital'], dictionary['currency']))

Readability Tips

Note that, like all structures within brackets, you can split a list comprehension into multiple lines:

data = [{'country':coun, 'capital': cap, 'currency': curr}
        for coun, cap, curr in zip(country, capital, currency)
       ]

You may also want to save the string to format in a variable (possibly with other constants) as well so that it does not end up buried inside other statements:

message = "Capital of {0} is {1} and currency is {2}"
for dictionary in data:
    print(message.format(dictionary['country'],dictionary['capital'], dictionary['currency']))

You can also specify the keys in the format space instead of {0} {1} then use .format_map to map the keys from the dictionary to the string:

message = "Capital of {country} is {capital} and currency is {currency}"
for dictionary in data:
    print(message.format_map(dictionary))

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