104k views
0 votes
Write it in Python

Change the following list to a list of dictionaries: - countries = [[('India', 'Mumbai') ],[( China', 'Shanghai') ],[( Finland', 'Tampere') ].

User Sabisabi
by
7.4k points

1 Answer

4 votes

Final answer:

To convert the given list into a list of dictionaries in Python, use a list comprehension and a dictionary comprehension.

Step-by-step explanation:

To convert the given list into a list of dictionaries in Python, we need to iterate over each sublist and extract the values to create dictionaries. Here's the code:

countries = [[('India', 'Mumbai')], [('China', 'Shanghai')], [('Finland', 'Tampere')]]
result = [{key: value for key, value in sublist[0]} for sublist in countries]
print(result)

This code uses a list comprehension to iterate over each sublist in the 'countries' list. It then extracts the values from each tuple using a dictionary comprehension and creates a dictionary. Finally, the resultant dictionaries are stored in a new list called 'result'.

User Andy Dwyer
by
8.1k points