Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading