oneman
oneman

Reputation: 811

How to create an 'contact book' in python using dictionaries?

I'm trying to create an contact book indexed by 'nickname' that allows the user to save a persons name, address and number. But I don't quite understand how to do it using dictionaries, if I had it my way I would just use a list. e.g

myList = [["Tom","1 Fairylane", "911"],["Bob","2 Fairylane", "0800838383"]]

And then if I wanted to see a certain contact I would just use some more code to search for a pattern. But I just can't figure out how to do it with a dictionary

Upvotes: 1

Views: 7016

Answers (3)

Selcuk
Selcuk

Reputation: 59229

You can start with this:

my_dict = {"Tom": {"name": "Tom Jones", "address": "1 Fairylane", "phone": "911"}, 
           "Bob": {"name": "Bob Marley", "address": "2 Fairylane", "phone": "0800838383"}
           }

then you can simply access records using

my_dict["Tom"]["name"]

or

my_dict["Bob"]["phone"]

Upvotes: 3

En-code
En-code

Reputation: 49

As mentioned by DomTomCat you could set the dictionary key to be the first name, and the data then contained in a list. One thing to note is that dictionaries are unsorted. So whilst they provide a very fast search (they are essentially a hash table) for a key it will require you to do a bit of work if you wish to display sorted subsets of results.

Upvotes: 2

DomTomCat
DomTomCat

Reputation: 8569

Keys in a dictionary a unique. So if you have a list of contacts with no name twice you can use code like this:

contacts = {}
contacts['Tom'] = ["1 Fairylane", 911]
contacts['Bob'] = ["2 Fairylane", 0800838383]

so adding data to a dictionary is based on the access operator []. If you want to initialize a dictionary with ready data, use code like this:

contacts = {'Tom' : ["1 Fairylane", 911],
            'Bob' : ["2 Fairylane", 0800838383]}

access to a certain contact works like this:

print(contacts['Tom'])

Note, if you've got a second, say "Tom", this wouldn't work. You'd have to add date of birth or lastname or whatever to make it unique

Upvotes: 2

Related Questions