Python Forum
creating an 'adress book' in python using dictionaries?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
creating an 'adress book' in python using dictionaries?
#1
hello dear Python-experts


i am currently creating  an 'adress book' python where i want to use dictionaries?

the plan:
I'm trying to create an little adress-book that has got an index 
the index - think would be apropiate - could be the  'nickname' in the adress-book 
I want to give some options:

with the nickname the user can do some savings:

a. save a name of a person, the address of a person and subsequently the  phone-number of that person.
well - so far so good: - i want to use use a dictionaries, i want to have such a list. e.g

myList = [["Bill","Butcher", "4433345411"],["Billiboy","2 Rue Rivoli ", "0994399394800838383"]]
And then if I wanted to see a certain contact I would just use some more code to search for a pattern. 
And then i need to figure out how to do it with a dictionary?
well - i could do some starting points  - with the usage of a dictionary: 

i could probably start with this:

my_dict = {"Don": {"name": "Donald Jones", "address": "1 Rue Rivoli Paris ", "phone": "9444444411"}, 
           "Joseph": {"name": "Joseph Boy", "address": "3 Tivoli Paris", "phone": "0800838383"}
            "Bilbo": {"name": "Bilbo Baggin", "address": "4 White House Washington", "phone": "08055550838383"}
         
         }
         
But how to get access to the records that i have created: well i can access records using

my_dict["Don"]["name"]
or like so
my_dict["Bilbo"]["phone"]
BTW
: Keys in a Python dictionary tend to be  unique. Having a list of contacts in my adressbook the important thing is - there should be no name twice.  That saind - we see that  i can have the solution like this:
contacts = {}
contacts['Don'] = ["1 Rue Rivoli", 9444444411]
contacts['Joseph'] = ["3 Tivoli", 0800838383]
so adding data to a dictionary is based on the access operator []. 

the question is: how to extend the scipt a bit
should i make use of

- raw input
- arg.pop

how would you extend the script!?

what do you say!?



love to hear from you
apollo LOL
Wordpress - super toolkits a. http://wpgear.org/ :: und b. https://github.com/miziomon/awesome-wordpress :: Awesome WordPress: A curated list of amazingly awesome WordPress resources and awesome python things https://github.com/vinta/awesome-python
Reply
#2
I think you should do something like this -
adressDict = {'phony' : {'name' : 'Phony Phony', 'phone' : 'PhonyNum', 'adress' : 'Pony adress'}}

def addPerson():
    nickname = input('Type a nickname for the person\n - ')
    name = input('Type their full name\n - ')
    adress = input('Type their adress\n - ')
    phone = input('Type their phone number\n - ')
    add = False
    for i in adressDict:
        if i.lower() == name.lower():
            print('Name already there')
        elif adressDict[i]['name'].lower() == name.lower():
            print('Name already there')
        else:
            add = True
    if add:
        adressDict.update({nickname : {'name' : name, 'phone' : phone, 'adress' : adress}})

def indexPerson():
    name = input('Type the person\'s name or nickname\n - ')
    for i in adressDict:
        if i.lower() == name.lower() or adressDict[i]['name'].lower() == name.lower():
            print('\nName: %s\nPhone Number: %s\nAdress: %s\n' %(adressDict[i]['name'], adressDict[i]['phone'], adressDict[i]['adress']))
        else:
            print('Name not found')
        
def yesNo():
    yesNo = input('Would you like to add a person to the adress book y/n \n - ')
    if yesNo == 'n':
        indexPerson()
    elif yesNo == 'y':
        addPerson()
    else:
        print('Invalid response')


def main():
    while True:
        yesNo()
        Quit = input('Would you like to quit y/n \n - ')
        if Quit == 'n':
            pass
        elif Quit == 'y':
            break
        else:
            print('Invalid response')

main()
quit()
You can also use pickle to save everything to a txt document
Reply
#3
dictionaries contain indexes by default
my_dict = {
    "Don": {
        "name": "Donald Jones", 
        "address": "1 Rue Rivoli Paris ", 
        "phone": "9444444411"
    }, 
    "Joseph": {
        "name": "Joseph Boy", 
        "address": "3 Tivoli Paris", 
        "phone": "0800838383"
    },
    "Bilbo": {
        "name": "Bilbo Baggin",
        "address": "4 White House Washington",
        "phone": "08055550838383"
    }
}

def fetch_details(name):
    print(f'\nWhat we know about {name}')
    for key, value in my_dict[name].items():
        print(f'{key}: {value}')

fetch_details('Joseph')
fetch_details('Don')
output:
Output:
What we know about Joseph name: Joseph Boy address: 3 Tivoli Paris phone: 0800838383 What we know about Don name: Donald Jones address: 1 Rue Rivoli Paris phone: 9444444411
Reply
#4
Dictionary keys must be unique, so you can't have two contacts with same nickname. It's quite probable that you will face the situation when you want to make entry but can't because nickname is already 'taken'.

One way to overcome this is to use list of dictionaries (or list on named tuples). This way there will be no collision of nicknames:

contacts = [{"nickname": "Don", "name": "Donald Jones", "address": "1 Rue Rivoli Paris ", "phone": "9444444411"}, 
            {"nickname": "Joseph", "name": "Joseph Boy", "address": "3 Tivoli Paris", "phone": "0800838383"},
            {"nickname": "Bilbo", "name": "Bilbo Baggin", "address": "4 White House Washington", "phone": "08055550838383"}]
One can write some utility functions, for example adding contacts (note, that these are required keyword arguments):

def add_contact(*, nickname, name, address, phone):
    contacts.append({"nickname": nickname, "name": name, "address": address, "phone": phone})
Search function can be also handy (enables to search with exact match or partial match):

def find_contact(*, field, value, exact=True):
    return [row for row in contacts if (value in row[field], row[field] == value)[exact]]
Some examples:

>>> add_contact(nickname='Monkey-man', name='Arthur Dent', address='Cottington, West Country, Earth', phone='42')
>>> contacts
[{'nickname': 'Don', 'name': 'Donald Jones', 'address': '1 Rue Rivoli Paris ', 'phone': '9444444411'},
{'nickname': 'Joseph', 'name': 'Joseph Boy', 'address': '3 Tivoli Paris', 'phone': '0800838383'}, 
{'nickname': 'Bilbo', 'name': 'Bilbo Baggin', 'address': '4 White House Washington', 'phone': '08055550838383'}, 
{'nickname': 'Monkey-man', 'name': 'Arthur Dent', 'address': 'Cottington, West Country, Earth', 'phone': '42'}]
>>> find_contact(field='nickname', value='Don')
[{'nickname': 'Don', 'name': 'Donald Jones', 'address': '1 Rue Rivoli Paris ', 'phone': '9444444411'}]
>>> find_contact(field='name', value='Jo', exact=False)
[{'nickname': 'Don', 'name': 'Donald Jones', 'address': '1 Rue Rivoli Paris ', 'phone': '9444444411'}, 
{'nickname': 'Joseph', 'name': 'Joseph Boy', 'address': '3 Tivoli Paris', 'phone': '0800838383'}]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
hello dear perfringo, Larz60+, SheeppOSU,


many many thanks for the quick and in depth going answer. You have helped me alot and gave me many many good hints.
And i am also at the starting point with Python.

So i am very glad for any and all help.

You have helped me quite alot - and you encouraged me in going on.

Many many thanks!

have a great day!!

yours Apollo Smile

by the way: besides the ideas - a real DB could be make sense. SQLite would probably be sufficient. For me as a beginner in Python i guess that learning to use an ORM is a good thing and worth the effort on such a trivial first example like an tiny address book. What do you think?

Wink
Wordpress - super toolkits a. http://wpgear.org/ :: und b. https://github.com/miziomon/awesome-wordpress :: Awesome WordPress: A curated list of amazingly awesome WordPress resources and awesome python things https://github.com/vinta/awesome-python
Reply
#6
apollo Wrote:SQLite would probably be sufficient
Sure. For a small database, you could even start with tinydb, which is a also based on python dictionaries.
Reply
#7
There are many option for small stuff like a address book.
In Python standard library sqlite3.
TinyDB or dataset a tutorial here.
For Web i like Flask with Flask-SQLAlchemy.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Beginner stuck in Python book for kids mic81k 11 1,194 Nov-27-2023, 04:28 AM
Last Post: deanhystad
  Deitel book "Python for Programmers" ricardian 7 22,739 May-12-2023, 01:33 PM
Last Post: snippsat
  best " Learning Python " book for a beginner alok 4 3,045 Jul-30-2021, 11:37 AM
Last Post: metulburr
  Nested Python functions (Dan Bader's book) Drone4four 4 2,558 Jun-26-2021, 07:54 AM
Last Post: ndc85430
  I really need help, I am new to python, I am using a book that helps me to learn JaprO 5 2,976 Nov-28-2020, 02:30 PM
Last Post: JaprO
  Creating a list of dictionaries while iterating pythonnewbie138 6 3,271 Sep-27-2020, 08:23 PM
Last Post: pythonnewbie138
  listdir on IP Adress OEMS1 3 2,891 Jul-19-2020, 06:01 PM
Last Post: bowlofred
  Creating Nested Dictionaries Confusion gw1500se 2 2,132 May-18-2020, 11:16 PM
Last Post: gw1500se
  creating a list of dictionaries from API calls AndrewEnglsh101 5 3,063 Apr-03-2020, 02:21 PM
Last Post: AndrewEnglsh101
  Data Dictionaries in Python mrsenorchuck 16 7,332 Nov-25-2019, 09:29 PM
Last Post: mrsenorchuck

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020