python - 创建字典时 : TypeError: unhashable type: 'dict'

标签 python python-2.7 dictionary

我正在尝试编写一个简单的 Character Generator 脚本,我可以将其用于笔和纸 RPG。我正在考虑将我的所有信息存储在嵌套字典中并将其保存到 JSON 文件中。

但是,在创建以下字典时,我收到错误消息:

nhashable type: 'dict', focussing on {'cha': 1}}}

core_phb = {
'races': {
    'Human': {
        {'abilities': 'None'},
        {'alignment': 'Neutral'},
        {'size': 'Medium'},
        {'speed': 6},
        {'languages': 'Common'},
        {'ability_modifiers': {
            {'str': 1},
            {'dex': 1},
            {'con': 1},
            {'int': 1},
            {'wis': 1},
            {'cha': 1}}}
    },
    'Dwarf': {
        {'abilities': [
            'ability1',
            'ability2'
            ]},
        {'alignment': 'Lawful Good'},
        {'size': 'Medium'},
        {'speed': 5},
        {'languages': [
            'Common',
            'Dwarven'
            ]},
        {'ability_modifiers': [
            {'con': 2},
            {'wis': 1}
            ]}
    },
    'Elf': {
        {'abilities': [
            'ability1',
            'ability2'
            ]},
        {'alignment': 'Chaotic Good'},
        {'size': 'Medium'},
        {'speed': 6},
        {'languages': [
            'Common',
            'Elven'
            ]},
        {'ability_modifiers': [
            {'dex': 2},
            {'int': 1}
            ]}
    }
},
'classes': {
    {'Fighter': {}},
    {'Ranger': {}},
    {'Wizard': {}}
},
'ability_scores': [
    {'Str': 'str'},
    {'Dex': 'dex'},
    {'Con': 'con'},
    {'Int': 'int'},
    {'Wis': 'wis'},
    {'Cha': 'cha'}]
}

我只是想创建字典,而不是从中调用任何键。

据我了解 TypeError: unhashable type: 'dict' ,我可以使用 frozenset() 来获取 key 。

有没有更好的方法来完成我想做的事情?

最佳答案

您似乎在为 Python 制作字典 {...} 不正确。

列表看起来像这样:

[ {'a': 1}, {'b': 1}, {'c': 1} ]

字典看起来像这样:

{ 'a': 1, 'b': 2, 'c': 3 }

如果我猜对了你想要的行为,那么你可能想要这样的东西:

human = {
    'abilities': 'None',
    'alignment': 'Neutral',
    'size': 'Medium',
    'speed': 6,
    'languages': 'Common',
    'ability_modifiers': {
        'str': 1,
        'dex': 1,
        'con': 1,
        'int': 1,
        'wis': 1,
        'cha': 1
    }
}

关于python - 创建字典时 : TypeError: unhashable type: 'dict' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33580983/

相关文章:

python-2.7 - 无法识别“pip ”

css - 在css中制作背景图像贴图

python - 将隐藏数据插入组合框pyqt

python - Caffe for windows 中的未知图层类型(裁剪)

python - 将字符串中的每个字符替换为字典中的 float ,并将所有替换值相加

python - 如何在Python中从字典中打印2个或更多随机键

java - Java Swing 中的表

python - 将列表列表解析为字典到 pandas DataFrame 时忽略错误

python - 是否可以覆盖 "self"以指向 python 中 self.method 中的另一个对象?

python - 如何在 python 的 Axes3D 中使用循环绘制图例?