Ok so i am trying to do some basic while loop to show text formated in this way:
A - 80%-100%
B - 60%-80%
C - 50-60%
D - less then 50%
with this code:
dictionary={'A':'80%-100%','B':'60%-80%','C':'50-60%','D':'less then 50%'}
klucze=list(dictionary.keys())
q=0
while q<4:
print(klucze[q]," - ",dictionary[q])
q =1
It's working with klucze[q] only, but when i try to print dictionary[q] too, i get the error
CodePudding user response:
Instead of doing complicated things, use dict.items()
method that returns dictionary key-value.
dct = {'A':'80%-100%','B':'60%-80%','C':'50-60%','D':'less then 50%'}
for k, v in dct.items():
print(k, '-', v)
Output:
A - 80%-100%
B - 60%-80%
C - 50-60%
D - less then 50%
CodePudding user response:
Well dictionary accepts key to give you value at that key. Your dictionary has keys 'A', 'B', etc. But you are using numeric value to access dictionary values thus it does not works.
print(klucze[q]," - ",dictionary[klucze[q]])
Now the dictionary is getting key values you created as input so it will give you the correct output.
CodePudding user response:
Try this one. I replaced ' with " inside dict items.
dictionary={"A":"80%-100%","B":"60%-80%","C":"50-60%","D":"less then 50%"}
klucze=list(dictionary.keys())
q=0
while q<4:
print(klucze[q]," - ",list(dictionary.values())[q])
q =1