Loading...
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?
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.
Sign in as a tutor to answer this doubt.