em4995
em4995

Reputation: 77

Looping through list of dictionaries

My task is to make 3 dictionaries to store information about 3 people I know, such as their first name, last name, age, and the city in which they live:

Sissel = {'first_name': 'Sissel', 'last_name': 'Johnsen', 'age': '23', 'city': 'Copenhagen'}
David = {'first_name': 'David', 'last_name': 'Hansen', 'age': '35', 'city': 'Randers'}
Olivia = {'first_name': 'Olivia', 'last_name': 'Petersen', 'age': '57', 'city': 'New York'}

Then I had to store them in a list:

people = [Sissel, David, Olivia]

I have to loop through my list of people. And as I loop through the list, it has to print everything I know about each person by printing the key and associated values in each dictionary.

I tried using a for loop:

for k, v in people:
    print(k, v)

But I just got an error message saying

ValueError: too many values to unpack (expected 2)

Upvotes: 3

Views: 1380

Answers (3)

user2827262
user2827262

Reputation: 157

People is a list of dictionaries, which is why it throws a too many values to unpack error. In Python 3, you need to call dict.items():

for person in people:
    for k, v in person.items():
        print(k, v)
    print() # extra space between people

Upvotes: 2

codeoverflow
codeoverflow

Reputation: 21

for k, v in people:
    print(k, v)

people is a list. You can't unpack with k, v because there is only item each time in the for loop.

I would just add everyone to a one dictionary with lists, and print that way:

people = {'first_name': ['Sissel', 'David', 'Olivia'], 'last_name': ['Johnsen', 'Hansen', 'Petersen'],
              'age': ['23', '35', '57'], 'city': ['Copenhagen', 'Randers', 'New York']}
    
i = 0
while i < 3:
    for k, v in people.items():
        print(f'{k}:{v[i]}', end=', ')
    print('\n')
    i += 1

Upvotes: 0

Joe Ferndz
Joe Ferndz

Reputation: 8508

You are almost there. Here's what you need to do:

You have to iterate through the list. When you iterate through the list, you will pick up one element at a time. In your case, each element is a dictionary. So you need to use the key to get to the value.

for p in people:
    print (p['first_name: '])
    print (p['last_name: '])
    print (p['age: '])
    print (p['city: '])

Alternate to selecting each element, you can also do a for loop on the dictionary like this:

for p in people:
    for k,v in p.items():
        print (k,v)

Upvotes: 1

Related Questions