NoWiFi4U
NoWiFi4U

Reputation: 1

Is it possible to iterate/loop over keys, values of dictionaries nested in list?

So i am using crash course 2e.

I am on ex 6-7:"Start with the program you wrote for Exercise 6-1 (page 102). Make two new dictionaries representing different people, and store all three dictionaries in a list called

people . Loop through your list of people. As you loop through the list, print everything you know about each person."

I have my code formatted as follows(values have been replaced by 'value' for privacy reasons:


people = []

#add person to empty list

person = {
    'first_name' : 'value', 
    'last_name' : 'value', 
    'city' : 'value',
    }
people.append(person)

#add person to empty list

person = {
    'first_name' : 'value', 
    'last_name' : 'value', 
    'city' : 'value',
    }
people.append(person)

#add person to empty list

person = {
    'first_name' : 'value',
    'last_name' : 'value', 
    'city' : 'value',
    }
people.append(person)

#verify list has persons added

print(people)

Now for the for loop part, is it possible to access the keys and values associated with each dictionary in the list ? I tried but failed. i thought I could do what I do with dictionaries and for example do :

for key, value in people.items():

and then follow it up with an f-string inside a print call .

I know that if 'people' was a dictionary it would work but I am assuming that the following error occurred because it is a list: "AttributeError: 'list' object has no attribute 'items'"

So , in short:

Is it not possible to loop using .items() when it's a preceded by a list with dictionaries nested inside? How would I access each key, value pair in the above situation?

Is there an easier way then what I finally got to work:

for person in people:
    name = f"{person['first_name'].title()} {person['last_name'].title()}"
    residence = f"{person['city'].title()}"
    print(f"{name} lives in {residence}.")

Thanks in advance folks!

Upvotes: 0

Views: 69

Answers (1)

Stefan Schulz
Stefan Schulz

Reputation: 529

.items() does the trick

for list_entry in people:
    for propertie_ikey, propertie_item in list_entry.items():
        print(propertie_ikey, propertie_item)

Upvotes: 1

Related Questions