How to get 'name' attribute of item of string-array?

How do I return an item from an arbitrary dictionary object in Python?

  • I have a list of about 20 objects that are dictionary, and their attributes are all the same. I want the user to enter an object and return a specific item from its dictionary. I keep getting an error that says "'str' object has no attribute 'get'" though. Sure, here's the code (just one dictionary object) Zombie = {'name': 'Zombie','HP1': 49,'HP2': 60,'HP3': 90,'HP4': 120,'Atk1L1': 3,'Atk1L2': 3,'Atk1L3': 4,'Atk1L4': 5,'Atk1L1dmg': 1,'Atk1L2dmg': 2,'Atk1L3dmg': 2,'Atk1L4dmg': 3,'Atk2L1': 2,'Atk2L2': 2,'Atk2L3': 3,'Atk2L4': 4,'Atk2L1dmg': 2,'Atk2L2dmg': 3,'Atk2L3dmg': 4,'Atk2L4dmg': 4,'Atk3L1': 1,'Atk3L2': 1,'Atk3L3': 2,'Atk3L4': 3,'Atk3L1dmg': 3,'Atk3L2dmg': 4,'Atk3L3dmg': 4,'Atk3L4dmg': 5,'Dfns1': 1,'Dfns2': 2,'Dfns3': 2,'Dfns4': 3,} import random # this reads strings MonsterA = raw_input("Enter monster name: ") MonsterB = raw_input("Enter monster name: ") def rolldice (dice,roller): roll = 0 print roller," rolls with", dice, "dice" while dice > 0: d1 = random.randrange(1,6) roll = roll + d1 dice = dice -1 print roll # why are you calling get on a string? rolldice (MonsterA.get('Atk1L1'),MonsterA.get('name')) rolldice (MonsterB.get('Atk1L1'),MonsterB.get('name'))

  • Answer:

    MonsterA = raw_input("Enter monster name: ")  A string you enter at the prompt will be assigned to MonsterA, that's why you get an "'str' object has no attribute 'get'" error try this: MonsterA = dict(Zombie) MonsterA.name = raw_input("Enter monster name: ") rolldice(MosterA['Atk1L1'], MonsterA['name'])

Bruce Wang at Quora Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.