【问题标题】:How to print a dictionary made up of lines from a file in python3?如何在python3中打印由文件中的行组成的字典?
【发布时间】:2017-12-12 21:16:53
【问题描述】:

非常感谢任何帮助!谢谢

我有一个字典,由从这样的文件中提取的行组成:

Danny Shalev, 050-1111111, aaa@aaa.com
Gil Rom, 050-2222222, bbb@bbb.com
Tal Yakir, 050-3333333, ccc@ccc.com

编辑:我的目标是像这样打印出字典:

Danny Shalev - 050-1111111 - aaa@aaa.com
Gil Rom - 050-2222222 - bbb@bbb.com
Tal Yakir - 050-3333333 - ccc@ccc.com

名字是键,其余的是值。

我已经编写了将文件行转换为 dict 的代码,并且我想以特定格式打印出字典中的所有值,该格式将逐行,以“-”分隔。我已经编写了函数 print_person,要以这种格式打印出来,我只想将此函数(来自上一个类)应用到我的 dict 中。

代码如下:

class Person:
def __init__(self, name, phone,email):
    self.name = name
    self.phone = phone
    self.email = email

def print_person(self):
    return (str(self.name)+" - "+str(self.phone)+" - "+str(self.email))

class AddressBook:

def __init__ (self):
    self.contactsdict = {}

def add(self, newContact):
    self.contactsdict[newContact.name] = newContact.phone + " - " + newContact.email 


def search(self, name):
    return (self.contactsdict.get(name))

def addFromFile(self, fileName):
    f = open("contacts.txt") 
    for line in f:
        (key, val, val2) = line.split(",")
        self.contactsdict[key] = val + " - " + val2
    f.close

def printAddressBook(self):

    for key, val in self.contactsdict.items():
        Person.print_person


address = AddressBook() # make an instance

p1=Person("Danny Shalev","050-1111111","aaa@aaa.com")
print (p1.print_person())
address.add(p1)
address.addFromFile("contacts.txt")
address.printAddressBook()

我认为问题出在这部分,因为我不知道如何使用该方法:

def printAddressBook(self):

for key, val in self.contactsdict.items():
    Person.print_person

【问题讨论】:

  • 然后我得到这个错误:TypeError: print_person() missing 1 required positional argument: 'self'

标签: python-3.x class dictionary file-io


【解决方案1】:

这个

for key, val in self.contactsdict.items():
    Person.print_person

将所有字典条目解构为 2 个变量,一个是 key,另一个是 value。第二行是不正确的 - Person 是您的类,您需要该类的一个实例才能在其上使用定义的打印方法。 您可以在 Person 类的每个实例上调用 val.print_person() 以打印每个 IF 您将 Persons 存储在内部字典中。类是如何构造类的“模板”——必须使用实例来调用其函数。目前您的代码仅在内部字典中存储字符串。

将人员添加到您的内部字典替换

for line in f:
    (key, val, val2) = line.split(",")
    self.contactsdict[key] = val + " - " + val2

for line in f:
    (key, val, val2) = line.split(",")
    self.contactsdict[key] = Person(key,val,val2) # create instances of Persons
        # and store them in the dictionary by there name
        # you get collisions if your file contains persons with identical names    

修正代码(这个和其他一些用 cmets 标记的错误):

class Person:
    def __init__(self, name, phone,email):
        self.name = name
        self.phone = phone
        self.email = email

    def print_person(self):
        return (str(self.name) + " - " + str(self.phone) + " - " + str(self.email))

class AddressBook: 
    def __init__(self):
        self.contactsdict = {}

    def add(self, newContact):
        self.contactsdict[newContact.name] = newContact  # store the Person instance 
                                                         # under its name as key 

    def search(self, name):
        return (self.contactsdict.get(name))

    def addFromFile(self, fileName):
        f =  open("contacts.txt")
        for line in f:
            (key, val, val2) = line.split(",")
            self.add(Person(key,val,val2)) # create Person and use own add-Function 
                                           # to add it to internal dictionary
        f.close

    def printAddressBook(self): 
        for key, val in self.contactsdict.items():
            print( val.print_person() ) # you need to print the output 
                                        # of print_person() - it currently only 
                                        # returns the string and does not print it  

address = AddressBook() # make an instance
p1 = Person("Danny Shalev","050-1111111","aaa@aaa.com")
print(p1.print_person())
address.add(p1)
address.addFromFile("contacts.txt") 
address.printAddressBook()

搜索返回一个人,所以你可以用它来改变你的字典中的人:

print("")
p = address.search("Danny Shalev")
p.name = "Hallo"   # change the name of the found person (the key will still be "Danny Shalev")
address.printAddressBook()

输出:

Danny Shalev -  050-1111111 -  aaa@aaa.com
Gil Rom -  050-2222222 -  bbb@bbb.com
Tal Yakir -  050-3333333 -  ccc@ccc.com

Hallo -  050-1111111 -  aaa@aaa.com   # after change of searched person
Gil Rom -  050-2222222 -  bbb@bbb.com
Tal Yakir -  050-3333333 -  ccc@ccc.com 

【讨论】:

  • @YasmimFranceschi Mhh - 您没有将 Persons 添加到您的字典中,而是从文件中连接字符串 - 请参阅编辑以了解如何解决该问题
  • @YasmimFranceshci - 你为什么不使用你的 Add-Method 顺便说一句。为什么它也只将字符串放入字典中?你写的代码?
  • 是的,我写了代码。我有一个字典,作业任务要求我根据 print_person 方法中的格式使用 print_person 打印每个项目。但别在意错误,这是我的错误..
  • @YasmimFranceschi 我解决了问题如果可以,请标记答案。
  • 嘿,非常感谢,它看起来很棒,但我得到的结果很奇怪:{'Danny Shalev': <__main__.person object at>} :所以我替换了 print 以返回在本节中: def search(self, name): print (self.contactsdict.get(name))
猜你喜欢
  • 2018-09-12
  • 2017-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-25
  • 2013-12-23
  • 1970-01-01
相关资源
最近更新 更多