Move Python Dictionary From A Dictionary to Another

时光怂恿深爱的人放手 提交于 2019-12-02 11:47:44

You can assign the value (actually, a copy of the value) at key 'wooden_sword' in equipped dict to value from swords dict, then delete the value from swords:

...

equipped['wooden_sword'] = swords['wooden_sword'].copy()

del swords['wooden_sword']

print(swords)
print(equipped)

Output:

{}
{'wooden_sword': {'name': 'Wooden Sword', 'dmg': 1}}

If these dictionaries you're moving have more values other than int/str/float (other values such as lists/dicts/...), then consider using deepcopy to copy those inner values as well:

...
from copy import deepcopy

equipped['wooden_sword'] = deepcopy(swords['wooden_sword'])
...

Use something like:

equipped['wooden_sword'] = swords['wooden_sword'].copy()

I'd recommend to put another attribute to the sword instead of moving it, like this:

swords = {
        'wooden_sword': {
            'name': 'Wooden Sword',
            'dmg': 1,
            'equipped': True
        }
}

Like this you can just change an attribute inside 1 dictionary.

Assuming your "equipped" is a dictionary (signified by the fact you used curly brackets) you would do it like this:

equipped.update({'wooden_sword':swords['wooden_sword']})
del swords['wooden_sword']

I'd suggest use a class to keep an instance of the character's items. Then add whatever things you want, like swords, as attributes for that class like so:

class Equipment:
    def __init__(self):
        self.swords = {}

    def add_sword(self, sword):
        self.swords.update(sword)

Then you can have something like:

equipment = Equipment()

sword = {
    'wooden_sword': {'name': 'Wooden Sword', 'dmg': 1}
}

equipment.add_sword(sword)

Of course, you can also turn that sword dictionary into another class for a sword (which again, I recommend). Hope that helps and good luck with your game!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!