How do I print the number of items with 'for loops' in a list and dictionary? Here's my code:
for key, val in i.items():
print(key, val)
q = ["Quests: ", "Look at inventory, ", "Press 'r' or 'l'."]
for x in q:
print(x)
CodePudding user response:
Printing the number of items in the dictionary:
print(len(i.keys()))
Printing the number of items in the list:
print(len(q))
Not sure why you'd need a for
loop though.
CodePudding user response:
Not sure I understand but try that:
len(i)
This equals the length of dictionary 'i'. AKA number of items in it.
CodePudding user response:
I assume you are new to Python, since most tutorials on Python cover this basic concept pretty quickly.
If I understand your question correctly, you are trying something like:
for i in range(len(a_list)):
print(i)
You could then also access each item of a list with: a_list[i]
Note that this will not work the same way with a dictionary. a_dictionary[i]
would not get the i
th element. It would instead look for a key with the value i
.
I'd suggest you follow one of the many helpful tutorials online.
CodePudding user response:
There's two ways. The simplest is to use the length function len(). len(yourList) and len(yourDictionary) will give their sizes, aka the number of items in them.
However to do this manually, in case you iterate only part of a list you just create a counter variable. so
counter = 0
for key, value in i.items():
print(key, value)
counter = 1
print(counter)