Print class instance attribute from Python dictionary

Question:

For a dungeon crawler, I need to print a class instance attribute, ‘.sell_price’ alongside the instance names from a dictionary which is being indexed. Each item in the ‘blacksmith_dict’ is a class instance. Every item, regardless of type, has the attribute ‘.sell_price’.

The first dictionary (shortened for brevity) looks like this:

blacksmith_dict = {
            'Weapons': [short_sword, short_axe, quantum_sword, broad_sword...]...
            'Armor': [leather_armor, studded_leather_armor....].........
        }

From this, I create another dictionary for the player to pick the item TYPE:

            # create a list of blacksmith item types:
            item_type_lst = list(blacksmith_dict.keys())
            # create a dictionary from list of blacksmith items types, print out, add 1 to indexing
            item_type_dict = {}
            for item_type in item_type_lst:
                item_type_dict[item_type] = item_type_lst.index(item_type)
            for key, value in item_type_dict.items():
                print(value + 1, ':', key)
            

...

                try:
                    item_type_index_to_buy = int(input(f"Enter the number for the item type: "))
                    item_type_to_buy = item_type_lst[item_type_index_to_buy - 1] 
                except (IndexError, ValueError):
                    print("Invalid entry..")
                    sleep(1)
                    continue..

After the player chooses the type, another dictionary is created to choose the actual item, by index, from very similar code:

                    print(f"{item_type_to_buy} for sale:")
                    item_dict = {}
                    blacksmith_dict[item_type_to_buy].sort(key=lambda x: x.sell_price)
                    for item in (blacksmith_dict[item_type_to_buy]):
                        item_dict[item] = (blacksmith_dict[item_type_to_buy]).index(item)
                    for key, value in item_dict.items():
                        print(value + 1, ':', key)
                    print(f"Your gold: {self.gold} GP")

Currently, I can successfully get this output:

Armory for sale:
1 : Weapons
2 : Armor
...

Enter the number for the item type: 1
...
 Weapons for sale:
1 : Short Sword 
2 : Broad Sword
...
Your gold: 500000 GP
(P)ick item by number, or go (B)ack:

I need a way to add the ‘sell_price’ attribute alongside each item (class instance).

Asked By: misfit138

||

Answers:

Ok, I figured this out after many days, using repr for each object instance, like so:

    def __repr__(self):
        return f"{self.name} - Damage Bonus: {self.damage_bonus}  To hit: {self.to_hit_bonus}  Purchase Price: {self.buy_price} GP"

Now the output lists all pertinent information defined in the return statement.

Answered By: misfit138
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.