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

Ste*_*ncé 3 python dictionary python-2.7

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

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

nhashable type: 'dict', focussing on {'cha': 1}}}
Run Code Online (Sandbox Code Playgroud)
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'}]
}
Run Code Online (Sandbox Code Playgroud)

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

据我从TypeError: unhashable type: 'dict'了解到,我可以用来frozenset()获取密钥。

有更好的方法来做我想做的事情吗?

Joh*_*ich 5

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

列表如下所示:

[ {'a': 1}, {'b': 1}, {'c': 1} ]
Run Code Online (Sandbox Code Playgroud)

字典看起来像这样:

{ 'a': 1, 'b': 2, 'c': 3 }
Run Code Online (Sandbox Code Playgroud)

如果我正确地猜测你想要的行为,那么你可能想要这样的东西:

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
    }
}
Run Code Online (Sandbox Code Playgroud)