Reputation: 1245
I am making a game in Python and am storing dictionaries in lists as items:
equipped = {}
swords = {
'wooden_sword': {'name': 'Wooden Sword', 'dmg': 1}
}
How would I move the wooden_sword
item into the equipped
lists.
(If i am not using correct terminology feel free to edit)
Upvotes: 0
Views: 3139
Reputation: 342
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']
Upvotes: 1
Reputation: 252
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!
Upvotes: 1
Reputation: 56
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.
Upvotes: 2
Reputation: 22776
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'])
...
Upvotes: 2