如何从函数中添加第二个条目到python字典

时间:2015-09-22 04:37:59

标签: python list function dictionary input

我有一个列表,在列表中我想列出包含名称的列表的第一项,第二项包含与该名称相关的字典,例如:

[['James',{'name':'Thor', 'age':'30', 'race':'human', 'class':'fighter'}],['Tim',{'name':'Sally', 'age':'28', 'race':'half-orc', 'class':'cleric'}]]

目前我的功能代码是:

def add(chars):
    thisChar = []
    newChar = dict()
    print type(newChar)
    print type(chars)
    name = raw_input("What is your name? ").strip()
    thisChar.append(name)
    for field in attributes:
        userInput = raw_input("What is your " + field + "?")
        newChar[field] = userInput
    thisChar.append(newChar)
    chars.append(thisChar)
    return chars

但是在第二次传递时会抛出类型错误异常。我在这里错过了什么?

我的完整代码是:

attributes = ["Race", "Class", "Level", "Hit points", "Speed", "Initiative Bonus", "Strength", "Constitution", "Dexterity"
, "Inelegance", "Wisdom", "Charisma", "Armor class", "Fortitude", "Reflex", "Will Power", "Passive Insight", "Passive Perception"]


chars = []

def display(chars):
    print chars
    return

def add(chars):
    thisChar = []
    newChar = dict()
    name = raw_input("What is your name? ").strip()
    thisChar.append(name)
    for field in attributes:
        userInput = raw_input("What is your " + field + "?")
        newChar[field] = userInput
    thisChar.append(newChar)
    chars.append(thisChar)
    return chars

while True:
    print "Welcome to the D&D 4th edition Dungeon Master reference"
    print "D - Display "
    print "A - Add "
    print "Q - Quit"
    userChoice = raw_input("What would you like to do? ")
    userChoice.lower()
    if userChoice == "d":
        chars = display(chars)
    elif userChoice == "a":
        chars = add(chars)
    else:
        print "Bye"
        quit()

我的完整错误是:

Traceback (most recent call last):
  File "C:/****/Python/charDisplay/AddAndShow.py", line 133, in <module>
    chars = add(chars)
  File "C:/****/Python/charDisplay/AddAndShow.py", line 120, in add
    chars.append(thisChar)
AttributeError: 'NoneType' object has no attribute 'append'

1 个答案:

答案 0 :(得分:1)

问题很可能在这一行 -

chars = display(chars)

函数display()返回None,因此当您将其设置回chars时,您将chars设置为None,因此当您尝试时要使用此add()再次致电chars,它会给您错误。

您无需重新设置display()的结果。你可以做 -

if userChoice == "d":
    display(chars)

另一个问题,这一行没有做任何事情 -

userChoice.lower()

.lower()返回小写的stirng,它不会就地更改字符串(它不能,因为字符串是不可变的),你必须将返回的值分配给userChoice。示例 -

userChoice = userChoice.lower()