1

I have the following class setup:

class Card(object):
    def __init__(self, name="", attack=0, defense=0, magic=0, shield=0, description=""):
        self.name = name
        self.attack = int(attack)
        self.defense = int(defense)
        self.magic = int(magic)
        self.shield = int(shield)
        self.description = description

I would like to make instances of Card using a list of dictionaries created from csv.dictreader.

Here is what the method for determining my cardList returns:

[
{'Magic': '200', 'Shield': '100', 'NameOfCard': 'Knight', 'Attack': '700', 'Defense': '400', 'Description': ''},
{'Magic': '500', 'Shield': '500', 'NameOfCard': 'Mage', 'Attack': '0', 'Defense': '0', 'Description': ''},
{'Magic': '100', 'Shield': '100', 'NameOfCard': 'Peasant', 'Attack': '100', 'Defense': '100', 'Description': ''},
{'Magic': '0', 'Shield': '0', 'NameOfCard': 'Lancer', 'Attack': '400', 'Defense': '100', 'Description': ''},
{'Magic': '100', 'Shield': '200', 'NameOfCard': 'Guardian', 'Attack': '100', 'Defense': '600', 'Description': ''},
...]

I was hoping to be able to use the 'NameOfCard' values to name the instances, and then map the values to the arguments taken by the __init__ method in the Card class.

My first thought was to do something like this:

Knight = Card(cardList[0]('NameOfCard')...)

But calling print Knight.name returns TypeError: 'dict' object is not callable.

How do I use my list of dicts to create instances of the Card class?

2 Answers 2

3

Use argument unpacking:

knight = Card(**dict_of_properties)

This will expand dict_of_properties into named arguments:

knight = Card(name='foo', stuff='bar')

Assuming dict_of_properties looks like:

dict_of_properties = {
    'name': 'foo',
    'stuff': 'bar'
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This worked, just like the above answer too. I did not know about the ** ability.
2

If the argument names were the same as the dict keys then you could use:

Knight = Card(**cardList[0])

As it is you'll need to map the dict keys to the proper argument names first.

1 Comment

I reworked the csv file to make the keys match. Thanks! I did not know about the ** ability.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.