0

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?

Merjit
  • 167
  • 1
  • 10

2 Answers2

4

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.

-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
Joel Brun
  • 1
  • 2
  • 1
    This answer demonstrates a fundamental misunderstanding of the benefits of a dictionary, and the use of scope to access variables is somewhat unwise. – jonrsharpe Dec 11 '14 at 23:07
  • I know, but it does respond the question. I think the method phonebook is like a reverse phone lookup... – Joel Brun Dec 11 '14 at 23:08
  • Reverse `phone_numbers` and pass it in as a parameter; then it's a trivial `O(1)` lookup in local scope. – jonrsharpe Jan 20 '16 at 18:00
  • great idea the reverse phone_numbers. but iCodez asked how to do it with a method : def phonebook(number) and a dictionary based on the user for key. if the reverse dictionnary is not available than only a full scan will give you the name linked to a number. – Joel Brun Feb 03 '18 at 22:15
  • This is going to take a really long time at two years per comment. I'm out. – jonrsharpe Feb 03 '18 at 22:27
  • a really long time :). someone is busy. great for you ;) if you have no response let someone else respond. bye – Joel Brun Feb 03 '18 at 22:31
  • for someone interesed on reverse dictionnary. here a link to a old question about it. https://stackoverflow.com/questions/483666/python-reverse-invert-a-mapping – Joel Brun Feb 03 '18 at 22:34