May-04-2019, 07:49 PM
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:
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.
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.