Search code examples
pythonpython-3.xlistdictionarylist-comprehension

List Comprehension for List of Dictionary to get Values Separately for Each Key


I want to get the city names and their respective population in separate list from a given list of dictionary. I have achieved this using naive method and using map() function as well but I need it to be executed using List Comprehension technique. I have tried below code but it is not giving proper output. What modifications should I do, please comment. Thanks.

towns = [{'name': 'Manchester', 'population': 58241}, 
         {'name': 'Coventry', 'population': 12435}, 
         {'name': 'South Windsor', 'population': 25709}]

print('Name of towns in the city are:', [item for item in towns[item]['name'].values()])
print('Population of each town in the city are:', [item for item in towns[item]['population'].values()])

** Expected Output **

Name of towns in the city are: ['Manchester', 'Coventry', 'South Windsor']

Population of each town in the city are: [58241, 12435, 25709]


Solution

  • try this :

    towns = [{'name': 'Manchester', 'population': 58241}, 
             {'name': 'Coventry', 'population': 12435}, 
             {'name': 'South Windsor', 'population': 25709}]
    
    print('Name of towns in the city are:',
          [town['name'] for town in towns])
    print('Population of each town in the city are:',
          [town['population'] for town in towns])
    

    output:

    Name of towns in the city are: ['Manchester', 'Coventry', 'South Windsor']
    Population of each town in the city are: [58241, 12435, 25709]