Back to community
Computer ScienceClass 11 (CBSE) Resolved

How do I loop through a dictionary's keys and values in Python?

I have a dictionary of student names and marks. I want to print each name with its mark but I only know how to loop through lists. How do I do it for a dictionary?

Asked by Sneha Iyer 29 45d ago
Need a Computer Science tutor? Browse verified Computer Science tutors near you.

1 answer

Accepted answer
6

A dictionary stores key-value pairs, and you can loop through them in a few ways. The cleanest is using .items(), which gives both the key and the value together: 'for name, mark in marks.items(): print(name, mark)'. This prints each student with their mark. If you write 'for name in marks:' you get only the keys, and you can fetch the value with 'marks[name]'. You can also use 'marks.keys()' for just keys or 'marks.values()' for just the values. For your case, .items() is ideal because you need both at once. Remember dictionaries are accessed by key, not by position, so there is no index like in lists.

S
Sanjay Pillai
355 pts· 45d ago

Sign in as a tutor to answer this doubt.