在不删除当前键的情况下向Dicts添加键

2024-09-25 02:38:03 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我正在为我的游戏制作一个清单系统,但是像往常一样,有一个错误。这当然是我的错,但我想不出办法来。我需要的代码添加到dict项不替换当前键。例如,一个玩家钓到一条鱼:

inventory = {} #This is the dict to hold all the items

for x in range(1,10):
    inventory['slot{0}'.format(x)] = {'type':'Fish'}
    break

但是如果你钓到两条鱼,它总是占据第一个位置

###Output: 
{'slot1':{'type':'Fish'}}

所以我试着做了一个if,一个关于插槽是否已满的声明,然后再试下一个

for x in range(1,10):
    if inventory['slot{0}'.format(x)] != {}:
        x += 1
    inventory['slot{0}'.format(x)] = {'type':'Fish'}
    break

以下是捕获的两条鱼的预期产量:

###Output

{'slot1':{'type':'fish'},'slot2':{'type':'fish}}

但是我得到一个关键错误,嵌套字典不存在。所以,我需要一些帮助。你知道吗


Tags: theinformatforoutputiftype错误
3条回答

下面是预期输出的代码。实际上,您正在尝试在分配dict键之前访问它。你知道吗

inventory = {} #This is the dict to hold all the items

for x in range(1,10):
    if 'slot{0}'.format(x) in inventory:
        x += 1
    inventory['slot{0}'.format(x)] = {'type':'Health'}
    break
print(inventory)

正如在评论中提到的,这确实是一个列表的工作。包括完整的字典版本。你知道吗

带列表:

def get_slot_x(inventory, x):
    return inventory[x]

def add_item(inventory, item):
    for i, v in enumerate(inventory):
        if v is None:
            inventory[i] = v
            break
    else:
        raise RuntimeError('nowhere to put item')

def empty_slot_x(inventory, x):
    inventory[x] = None

inventory = [None] * 10

使用dict:

slotname = lambda x: 'slot%d' % x

POSSIBLE_SLOTS = list(map(slotname, range(10)))

如果值为“无”,则表示为空:

def add_item(inventory, item):
    for k, v in inventory.items():
        if v is None:
            inventory[k] = v
            break
    else:
        raise RuntimeError('nowhere to put item')

def get_slot_x(inventory, x):
    return inventory[slotname(x)]

def empty_slot_x(inventory, x):
    inventory[slotname(x)] = None

inventory = collections.OrderedDict.fromkeys(POSSIBLE_SLOTS)

或者,如果不希望出现任何键,则表示为空:

def add_item(inventory, item):
    for k in POSSIBLE_SLOTS:
        if k not in inventory:
            inventory[k] = v
            break
    else:
        raise RuntimeError('nowhere to put item')

def get_slot_x(inventory, x):
    return inventory.get(slotname(x))

def empty_slot_x(inventory, x):
    inventory.pop(slotname(x), None)

inventory = {}

对于上述任何一项:

add_item(inventory, 'foobar')
assert get_slot_x(inventory, 0) is None
assert get_slot_x(inventory, 0) == 'foobar'
empty_slot_x(inventory, 0)  # You may want to throw errors if nothing is there
assert get_slot_x(inventory, 0) is None

您也可以完全删除slotname,如果没有按下键的原因,只使用整数作为键。你知道吗

您可以将新数据输入到新的dicttemp = {},然后将其与主dictinventory = {**inventory, **temp}合并

相关问题 更多 >