Python 创建具有未知键的词典并向其附加列表值?

Python 创建具有未知键的词典并向其附加列表值?,python,list,dictionary,Python,List,Dictionary,我希望能够在我的游戏中遍历所有对象并检查它们的self.owner属性 为此,我要: for ship in game_map._all_ships(): .... 我想制作一本以玩家为键的字典,并列出船只的价值: dictionary { 'Player 0' :[ship 1, ship 2], 'Player 1': [ship 1] ... etc} 我可以用它找回他们的球员 ship.owner 但是我不知道如何用列表初始化字典,而不知道有多少玩家或者他们有多少飞船,而

我希望能够在我的游戏中遍历所有对象并检查它们的self.owner属性

为此,我要:

for ship in game_map._all_ships():
     ....
我想制作一本以玩家为键的字典,并列出船只的价值:

dictionary { 'Player 0' :[ship 1, ship 2], 'Player 1': [ship 1] ... etc}
我可以用它找回他们的球员

ship.owner
但是我不知道如何用列表初始化字典,而不知道有多少玩家或者他们有多少飞船,而不先运行循环。

试试这个:

# create an empty dictionary
mydictionary = {}
# loop through all ship objects
for ship in game_map._all_ships():
    # check if there's not list yet for the ship owner
    if ship.owner not in mydictionary:
        # if no such list exists yet, create it with an empty list
        mydictionary[ship.owner] = []
    # with the ship owner name as key, extend the list with the new ship
    mydictionary[ship.owner].append(ship)

为了避免检查关键点,最平滑的方法使用:

from collections import defaultdict

dic = defaultdict(list)
for ship in game_map._all_ships():
    dic[ship.owner].append(ship)
这里需要的是一个围绕
dict
的包装类,它提供了所有基本的字典功能,并允许创建空值键值对

Pydoc将其定义为:

类集合.defaultdict([default_factory[,…])

返回一个新的类似字典的对象。defaultdict是内置dict的一个子类 班级。它重写一个方法并添加一个可写实例 变量其余功能与dict相同 类,此处没有记录

第一个参数提供默认工厂的初始值 属性默认为“无”。将处理所有剩余的参数 与将它们传递给dict构造函数相同,包括 关键字参数

小示例代码:

>>> from collections import defaultdict

# create defaultdict containing values of `list` type
>>> d = defaultdict(list)
>>> d
=> defaultdict(<class 'list'>, {})

# assuming we need to add list `l` value to the dictionary with key 'l'
>>> l = [1,2,3]
>>> for ele in l: 
        d['l'].append(ele)    

>>> d
=> defaultdict(<class 'list'>, {'l': [1, 2, 3]})
>>从集合导入defaultdict
#创建包含'list'类型值的defaultdict
>>>d=默认DICT(列表)
>>>d
=>defaultdict(,{})
#假设我们需要使用键“l”将列表“l”值添加到字典中
>>>l=[1,2,3]
>>>对于l中的ele:
d['l'].附加(ele)
>>>d
=>defaultdict(,{'l':[1,2,3]})

看一看DefaultDict,从空列表/目录开始,随着时间的推移不断增长,这是非常好的。