Python 3.x 如何向一个键添加一组多个值?

Python 3.x 如何向一个键添加一组多个值?,python-3.x,class,dictionary,set,Python 3.x,Class,Dictionary,Set,我创建了一个基本上是一本爱好书的类。这本书可以通过两种方法访问,enter(n,h),它取一个名字,并不断向名字中添加爱好(一个名字可以有多个爱好)。另一个方法返回特定名称的一组爱好。我的爱好书是存储每一个爱好,我插入到一个名字。有人能帮我修一下吗 class Hobby: def __init__(self): self.dic={} self.hby=set() def enter(self,n,h): if n not

我创建了一个基本上是一本爱好书的类。这本书可以通过两种方法访问,
enter(n,h)
,它取一个名字,并不断向名字中添加爱好(一个名字可以有多个爱好)。另一个方法返回特定名称的一组爱好。我的爱好书是存储每一个爱好,我插入到一个名字。有人能帮我修一下吗

class Hobby:

    def __init__(self):
        self.dic={}
        self.hby=set()

    def enter(self,n,h):

        if n not in self.dic.items():
            self.dic[n]=self.hby
                for k in self.dic.items():
                    self.hby.add(h)

    def lookup(self,n):
        return self.dic[n]
我试着处理以下案件

    d = Hobby(); d.enter('Roj', 'soccer'); d.lookup('Roj')
    {'soccer'}
    d.enter('Max', 'reading'); d.lookup('Max') 
    {'reading', 'soccer'} #should return just reading
    d.enter('Roj', 'music'); d.lookup('Roj')
    {'reading', 'soccer','music'} #should return soccer and music

你为什么要在这里发明一个
dict
?为什么要使用一个单独的集合来添加值,并将其引用到每个键,以确保它在查找时始终返回相同的集合

不要重新发明轮子,使用集合。defaultdict:

import collections

d = collections.defaultdict(set)
d["Roj"].add("soccer")
d["Roj"]
# {'soccer'}
d["Max"].add("reading")
d["Max"]
# {'reading'}
d["Roj"].add("music")
d["Roj"]
# {'soccer', 'music'}

更新-如果您真的想通过自己的课程完成(在完成之前,请观看!),您可以通过以下方式完成:

class Hobby(object):

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

    def enter(self, n, h):
        if n not in self.container:
            self.container[n] = {h}
        else:
            self.container[n].add(h)

    def lookup(self, n):
        return self.container.get(n, None)

d = Hobby()
d.enter("Roj", "soccer")
d.lookup("Roj")
# {'soccer'}
d.enter("Max", "reading")
d.lookup("Max")
# {'reading'}
d.enter("Roj", "music")
d.lookup("Roj")
# {'soccer', 'music'}

注意这里没有使用额外的集合-每个
dict
键都有自己的
set
来填充。

你为什么要在这里发明
dict
?为什么要使用一个单独的集合来添加值,并将其引用到每个键,以确保它在查找时始终返回相同的集合

不要重新发明轮子,使用集合。defaultdict:

import collections

d = collections.defaultdict(set)
d["Roj"].add("soccer")
d["Roj"]
# {'soccer'}
d["Max"].add("reading")
d["Max"]
# {'reading'}
d["Roj"].add("music")
d["Roj"]
# {'soccer', 'music'}

更新-如果您真的想通过自己的课程完成(在完成之前,请观看!),您可以通过以下方式完成:

class Hobby(object):

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

    def enter(self, n, h):
        if n not in self.container:
            self.container[n] = {h}
        else:
            self.container[n].add(h)

    def lookup(self, n):
        return self.container.get(n, None)

d = Hobby()
d.enter("Roj", "soccer")
d.lookup("Roj")
# {'soccer'}
d.enter("Max", "reading")
d.lookup("Max")
# {'reading'}
d.enter("Roj", "music")
d.lookup("Roj")
# {'soccer', 'music'}
注意这里没有使用额外的集合-每个
dict
键都有自己的
set
来填充