简体   繁体   中英

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. eg

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

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"]

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM