Reputation: 167
Let's say I have a dictionary like this:
phone_numbers = {'Ted': '555-222-1234', 'Sally': '555-867-5309'}
I'd like function that returns both the key and the value passed to it, e.g.:
>>> phonebook(phone_number['Ted'])
Ted's phone number is: 555-222-1234
In pseudocode, the function would be:
def phonebook(number):
print("{}'s phone number is: {}".format(
number.key(), # Not a real dictionary method!
number.value()) # Also not a real dictionary method!
Is there a way to do this without a lot of major back-end rewriting of types and classes?
Upvotes: 0
Views: 204
Reputation: 1
here is your answer :
def phonebook(phonenumber):
for name, number in phone_numbers.items():
if(number = phonenumber):
print("{}'s phone number is: {}".format(name, number)
return
Upvotes: -1
Reputation:
You will need to pass both the dictionary and the name that you want to lookup:
>>> phone_numbers = {'Ted': '555-222-1234', 'Sally': '555-867-5309'}
>>> def phonebook(dct, name):
... print("{}'s phone number is: {}".format(name, dct[name]))
...
>>> phonebook(phone_numbers, 'Ted')
Ted's phone number is: 555-222-1234
>>>
Doing phone_number['Ted']
simply returns the string phone number that is associated with the key 'Ted'
in the dictionary. Meaning, there is no way to trace this string back to the dictionary it came from.
Upvotes: 4