1

I am creating a dict to hold name and phone number, storing to local by pickle. the issue now I am facing is: it seems like the merge is not working fine. , any idea? thanks.

import pickle
def add(name,contact):
    person= {};  
    person[name] = contact;
    print('new added: ',person);

    mycontactfile = 'contactlist.txt';
    f = open(mycontactfile,'rb');
    storedcontact = pickle.load(f);
    f.close();
    print('saved list:',storedcontact);

    storedcontact.update(person); # add a new contact to the list

    f = open(mycontactfile,'wb');
    pickle.dump(storedcontact,f);

    print('now full list is:' ,storedcontact);
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 4
    Just a suggestion, you dont have to use `;` to indicate the end of line, like in C or C++ – thefourtheye Nov 15 '13 at 03:04
  • possible duplicate of [How can I merge (union) two Python dictionaries in a single expression?](http://stackoverflow.com/questions/38987/how-can-i-merge-union-two-python-dictionaries-in-a-single-expression) – aIKid Nov 15 '13 at 03:05
  • 1
    I found the reason, person and storedcontact has the same key, so output only shows one. thank you all though – user2986226 Nov 15 '13 at 03:10
  • 2
    Show exactly what the problem is. We can't guess what "not working fine" means. Note that instead of `update()`, you could more simply do `storedcontact[name] = contact`, and get rid of the `person` dict. – Tim Peters Nov 15 '13 at 03:11
  • @thefourtheye Can you go to the chat? I want to ask something – aIKid Nov 15 '13 at 03:12
  • instead of pickling every time you `add`, why don't you just use `shelve` and let it take care of serializing... – roippi Nov 15 '13 at 03:17
  • update is updating an existing dictionary ... I think you want a list of dictionaries ... – Joran Beasley Nov 15 '13 at 03:17
  • the output for above initially is new added: {'a': '1'} saved list: {'a': '1'} now full list is: {'a': '1'}, even though I add second record {'a':'1'}, the full list still shows {'a': '1'}, as I suppose to see 2 records. however I think I miss some logic, when the second record contains the same key in the dict, then it will be update(override the existing one) instead of inserting a fresh record. – user2986226 Nov 15 '13 at 03:22
  • being said, the code above is correct. – user2986226 Nov 15 '13 at 03:25

1 Answers1

0

If you have multiple contacts to go with a name, you'll need a dict of list. You would add contacts like this

if name in storedcontact:
    storedcontact.append(contact)
else:
    storedcontact[name] = contact

Better yet, stop using pickles and switch to sqlite

Aside: you can also initialise person in one step like this (but you don't really need person anymore)

person = {name: contact}
John La Rooy
  • 295,403
  • 53
  • 369
  • 502