I am having issues finding a way to have the below program search for any given string of "query" in the keys of the dictionary AB and return the value, or the key and value. Thus far I just done what I have preset in the dictionary; Ashley and Joshua, and they are retrievable via a very simple code, that is unrealistic if I wanted users to be able to create and search from their own Address Book dictionary.

#Address Book#
#Remember brackets call object from library []#
#only add dicts to dicts; add via dictname.update(var)
AB={'Joshua' : 'Joshua: ''Email: sho0uk0m0o@gmail.com Phone: (802) 3-5-2206',
    'Ashley' : 'Ashley: ''Email: a000@gmail.com Phone: (802) 820-0000',}
print('Address Book: Enter x into query to exit')
print('to add a contact enter "add" in query')
query = input('Enter Search Query: ')
##abkeys=AB.keys()
##abvals=AB.values()
while query!=('x'):
    if ('add')in query:
        new={input('Enter name: '): input('utilize the following format: Name______,:, Email,:,______, Phone,:,______ Enter contact information: ')}
        AB.update(new)
        print(AB)
        query=input('Enter Search Query: ')
##        if query in AB:
##            print(AB.keys(),AB.values())
    elif ('as') in query or ('As') in query:
        print(AB['Ashley'])
        query= input('Enter Search Query:' )
    elif ('jo') in query or ('Jo') in query:
        print(AB['Joshua'])
        query=input('Enter Search Query:' )
    elif query==('0'):
        print(AB['Joshua'])
        print(AB['Ashley'])
        query=('x')
    else:
        print('Query not found please retype your query or type "help" for more information')
        query = input('Enter Search Query: ')
if ('x') in query or query==('x'):
    print('Application Terminated')           
#Next, find a way to search based on any given input == str in key from AB and print key,value

Recommended Answers

All 10 Replies

I do not understand your format:

>>> AB={'Joshua' : 'Joshua: ''Email: sho0uk0m0o@gmail.com Phone: (802) 3-5-2206',
    'Ashley' : 'Ashley: ''Email: a000@gmail.com Phone: (802) 820-0000',}

>>> AB
{'Joshua': 'Joshua: Email: sho0uk0m0o@gmail.com Phone: (802) 3-5-2206', 'Ashley': 'Ashley: Email: a000@gmail.com Phone: (802) 820-0000'}
>>>

Sorry, I'm new to this, the address book has the names twice because the looked better when printed out to me. The later coding with if(as) in query was just me learning how to utilize the in function. But now I want to search with any given parameters from the user and print the corresponding contact (value or key:value pair)

For storing a few values, like phone number and e-mail address, you can use a list which is easier to understand and use.

AB={'Joshua' : ['sho0uk0m0o@gmail.com',  '(802) 3-5-2206'],
    'Ashley':  ['a000@gmail.com', '(802) 820-0000']}
print "%s,  e-mail=%s,  phone=%s" % ("Joshua", AB["Joshua"][0], AB["Joshua"][1])

new_name = "Bill"
new_email= "bill@domain.com"
new_phone= "(802) 123-4567"

AB[new_name] = [new_phone, new_email]
print AB

For storing a few values, like phone number and e-mail address, you can use a list which is easier to understand and use.

AB={'Joshua' : ['sho0uk0m0o@gmail.com',  '(802) 3-5-2206'],
    'Ashley':  ['a000@gmail.com', '(802) 820-0000']}
print "%s,  e-mail=%s,  phone=%s" % ("Joshua", AB["Joshua"][0], AB["Joshua"][1])

new_name = "Bill"
new_email= "bill@domain.com"
new_phone= "(802) 123-4567"

AB[new_name] = [new_phone, new_email]
print AB

thank you! that was extremely useful advice. Now, if I wanted the user of the program to be able to search for a contact they created, via entering the key as the query, how would I do that and return the value?

thank you! that was extremely useful advice. Now, if I wanted the user of the program to be able to search for a contact they created, via entering the key as the query, how would I do that and return the value?

You can retrieve values from a dictionary by passing it the key. For example:

query = raw_input("Please enter name.")
print AB[query]

Notice that I changed your input() method to raw_input(). raw_input will convert the input to a string, since that is what the user will be using as input.
The above code can give a KeyError exception, so be sure to surround the print statement with a try/except statement:

query = raw_input('Please enter your name.')
try:
	print AB[query]
except KeyError:
	print 'Name is not in Address Book.'

Notice that I changed your input() method to raw_input(). raw_input will convert the input to a string, since that is what the user will be using as input.

Thank you, that's extremely helpful as well. However, raw_input() has been giving me syntax errors for some reason. I don't know if it's because of the OS on this computer or if it's something new in 3.x. Any ideas?

If you are ready to use python 2, you can write it very easily using a class I wrote in this code snippet http://www.daniweb.com/software-development/python/code/258640 .
Here is a possible code

from optcmd import OptCmd

AB = dict()

class AddressBookCmd(OptCmd):
    def emtpyline(self):
        pass
    
    def do_add(self, name, email, phone):
        """
        usage: add name email phone
        
            Add an entry in the address book.
        """
        AB[name] = [email, phone]
        
    def do_get(self, name):
        """
        usage: get name

            Retrieve the address book's entry for name.
        """
        if name in AB:
            print("{n}\n\temail: {e}\n\tphone: {p}".format(
                  n = name, e = AB[name][0], p = AB[name][1]))
        else:
            print("No such name in the address book.")
                  
if __name__ == "__main__":
    cmd = AddressBookCmd()
    cmd.prompt = "[AB] "
    cmd.cmdloop("Welcome to the Address Book".center(72))


""" Example session

                      Welcome to the Address Book                       
[AB] add Joshua sho0uk0m0o@gmail.com "(802) 3-5-2206"
[AB] add Ashley a000@gmail.com "(802) 820-0000"
[AB] get Joshua
Joshua
	email: sho0uk0m0o@gmail.com
	phone: (802) 3-5-2206
[AB] get Woooee
No such name in the address book.
[AB] help get

usage: get name

    Retrieve the address book's entry for name.

[AB] quit
"""

I couldn't find the time to translate optcmd into python 3 until now ...

#Address Book#
#Remember brackets call object from library []#
#only add dicts to dicts; add via dictname.update(var)
AB={'Joshua' : ['Email: sho0uk0m0o@gmail.com Phone: (802) 3-5-2206'],
    'Ashley' : ['Ashley: ''Email: a000@gmail.com Phone: (802) 820-0000'],}
print('Address Book: Enter x into query to exit')
print('to add a contact enter "add" in query')
query = input('Enter Search Query: ')
while query!=('x'):
    try:
        print(AB[query])
        query=input('Enter another search query or x to exit: ')
    except KeyError:
        if ('add')in query:
            new={input('Enter name: '): [input('Enter contact information: ')]}
            AB.update(new)
            query=input('Enter Search Query: ')
        else:
            print('Name not in Address Book, remember contacts are case sensitive. Please try again.')
            query=input('Enter Search Query: ')
if ('x') in query or query==('x'):
    print('Application Terminated')

So I've updated based on everybody's suggestions and here is the product so far, it's doing exactly what I wanted. Next I'm going to figure out a way to utilize Woooee's first format into it. Gribouillis, I really appreciate the help, I'm just not sure how to utilize that to its best potential right now, too busy being a noob, sorry.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.