Search code examples
pythonlistdictionaryfor-loopkey-value-store

How do I use a for loop to return values from a key that features in all the dictionaries stored in a list?


How do I use a for loop to return all the ssn values from the dictionaries stored in this list:

patlist = [{'mrn': 7182, 'birthyear': 1989, 'ssn': '999-76-5071', 'fname': 'Edgar', 'lname': 'Hermann', 'zip': 72034},
            {'mrn': 7491, 'birthyear': 2018, 'ssn': '999-92-3312', 'fname': 'Dionna', 'lname': 'Heathcote', 'zip': 72411},
            {'mrn': 7052, 'birthyear': 2013, 'ssn': '999-80-4418', 'fname': 'Eleni', 'lname': 'Gusikowski', 'zip': 72736},
            {'mrn': 4851, 'birthyear': 2011, 'ssn': '999-51-6410', 'fname': 'Ricardo', 'lname': 'Mills', 'zip': 72046},
            {'mrn': 1744, 'birthyear': 1969, 'ssn': '999-72-5953', 'fname': 'Michelle', 'lname': 'Breitenberg', 'zip': 72472}]```


Here is one of my attempts:

for value in patlist['ssn']:
    print['ssn']

Thank you for any help.


Solution

  • Since patlist is list of dictionaries, the value is actually a dictionary. So you can do value['ssn'] to print the value of ssn key.

    patlist = [{'mrn': 7182, 'birthyear': 1989, 'ssn': '999-76-5071', 'fname': 'Edgar', 'lname': 'Hermann', 'zip': 72034},
                {'mrn': 7491, 'birthyear': 2018, 'ssn': '999-92-3312', 'fname': 'Dionna', 'lname': 'Heathcote', 'zip': 72411},
                {'mrn': 7052, 'birthyear': 2013, 'ssn': '999-80-4418', 'fname': 'Eleni', 'lname': 'Gusikowski', 'zip': 72736},
                {'mrn': 4851, 'birthyear': 2011, 'ssn': '999-51-6410', 'fname': 'Ricardo', 'lname': 'Mills', 'zip': 72046},
                {'mrn': 1744, 'birthyear': 1969, 'ssn': '999-72-5953', 'fname': 'Michelle', 'lname': 'Breitenberg', 'zip': 72472}]
    
    
    for value in patlist:
        print(value['ssn'])