Reputation: 111
I had a look through the other answers but couldn't really find an answer to mine.
The program needs to return a persons age given their name.
recordslist = [["Daniel", 18], ["John", 19], ["Paul", 20], ["Jack", 44]]
def(name):
checkAge(str(input("What is your name?")))
For example if Daniel is entered, the program returns 18. If John is entered, the program returns 19.
I'm not sure how to code this. There must be a for and in command somewhere in that def.
Thanks :-)
Upvotes: 0
Views: 86
Reputation: 12092
This is what you are looking for - dict(recordslist)
. A dictionary in Python is a key value pair. Your data can be better structured as a key value pair. Key being the name of the person and value being his/her corresponding score. dict(recordslist)
converts your data from a list of lists to a dictionary.
You can access the value corresponding to a key in a dictionary as:
dictionary_variable[key]
Demo:
>>> recordslist = [["Daniel", 18], ["John", 19], ["Paul", 20], ["Jack", 44]]
>>> a_dict = dict(recordslist)
>>> a_dict
{'John': 19, 'Paul': 20, 'Daniel': 18, 'Jack': 44}
>>> a_dict['Daniel']
18
In your code you would do:
def checkAge(name, a_dict):
if name in a_dict:
return a_dict[name]
else:
return "No score found for {}".format(name)
result = checkAge(str(input("What is your name?")))
print result
Note: In order for this to work as you expect it to, you must have unique names in your list of list. This is what I mean:
>>> recordslist = [["Daniel", 18], ["John", 19], ["Paul", 20], ["Jack", 44], ["Daniel", 40]]
>>> a_dict = dict(recordslist)
>>> a_dict
{'John': 19, 'Paul': 20, 'Daniel': 40, 'Jack': 44}
I added ["Daniel", 40]
to your recordslist
and the a_dict
has only one entry for Daniel
.
Upvotes: 1
Reputation: 103744
As shaktimaan suggested, a dict is the right data structure if you have unique names.
If you have multiple entries with the same name potentially, you can use a list comprehension:
>>> recordslist = [["Daniel", 18], ["John", 19], ["Paul", 20], ["Daniel", 22]]
>>> tgt="Daniel"
>>> [(name, age) for name, age in recordslist if name==tgt]
[('Daniel', 18), ('Daniel', 22)]
Upvotes: 0