+ 2
Need help
I need to print a list in a dict, here goes the code: coordinates={ 'me':[45, 32], 'school':[89, 37] } #if 'school'[1]==37: print('True') else: print('False') print('Your coordinates [x, y]:',coordinates['me'])
6 Réponses
+ 2
BTW I just try to print school's y-axis co-ordinates for testing, thank you
+ 2
coordinates = {
'me':[45, 32],
'school':[89, 37]
}
if coordinates['school'][1]==37: //<--
print('True')
else:
print('False')
print('Your coordinates [x, y]:', coordinates['me'])
In your if statement you need to first use the name of your dictionary, then use the key to get the school list. You can then use the index of the item you need in the list.
Like so:
coordinates['school'][1] // returns 37
This will return the item with the index of 1 in the list with the key of school in the dictionary coordinates.
You could also create a list variable from your dictionary first then access the item with the index of 1 like so:
schoolCoords = coordinates['school'] // returns [89, 37]
// schoolCoords is now [89, 37]
schoolCoords[1] // This will return 37
also here is some string formatting for you:
print('Your coordinates are [{}, {}]'.format(coordinates['me'][0], coordinates['me'][1]))
// prints --> Your coordinates are [45, 32]
EDIT:
BTW @Justin Hill
A string type in python is basically a list type so when we do:
'school'[1]
We are returning the value of the character at the index of 1 within the string school. Which is 'c'.
It's the same as if we did:
['s','c','h','o','o','l'][1] // returns 'c'
OR
school = ['s','c','h','o','o','l']
school[1] // returns 'c'
+ 2
Oh ty!
+ 2
I made it as a comment cuz it gave error and I was too lazy to use try and except
0
if you add this to your code, it will show you what 'school'[1] is showing..
print('school'[1])
which is resulting in "c" .. so, apparently checking inside quotes gives you the #1 index of the word.. we both learned something here..
so your code is reading false because
'school'[1]' == 'c'
and there is a # before the if which makes it a comment and not code
0
You have a # before the if statement. that turns it into a comment.