I am writing an address book on the book Byte of Pyton (task). When adding a new contact, it gives an error. Already tried different options, I can not understand what's the matter.

import shelve class PhoneBook(): mybook = {} f = shelve.open('mybook', flag='n') newbook = {} def add_person(self, newcont, new_phone): self.newcont = newcont self.new_phone = new_phone self.newbook = {self.newcont: self.new_phone} self.mybook.update([self.newbook]) f = self.mybook 

The following error: Before that there was no this error, but simply did not add it to the file.

 Traceback (most recent call last): File "C:/PythonWork/Kate/phonebookclassi.py", line 76, in <module> phonebook.add_person(newcont, new_phone) File "C:/PythonWork/Kate/phonebookclassi.py", line 12, in add_person self.mybook.update([self.newbook]) ValueError: dictionary update sequence element #0 has length 1; 2 is required 
  • And in your code where is the error string? - m9_psy
  • Updated the error, renders from the previous version threw off. - kelevra

1 answer 1

First of all, let's look at the documentation . It says which objects the update method accepts:

1) Another dictionary.

2) An iterable collection (list) consisting of key-value pairs.

3) Named arguments.

You give him a list with a dictionary, this option is not provided.

Three methods:

 # 1 Метод a = {"a": 1} b = {"c": 2} a.update(b) print(a) >>> {"a": 1, "c": 2} # 2 Метод a = {"a": 1} b = [("c", 2), ("yo", 199)] a.update(b) print(a) >>> {"a": 1, "c": 2, "yo": 199} # 3 метод a = {"a": 1} a.update(c=2, yo=199) print(a) >>> {"a": 1, "c": 2, "yo": 199}