简体   繁体   English

具有相同键的字典中的Python列表

[英]Python list inside a dictionary with the same keys

I am running a python program using Visual Studio Code, and the data for it looks like this: 我正在使用Visual Studio Code运行python程序,其数据如下所示:

data = {
    [0, 0, 0] : 0,
    [0, 0, 1] : 0,
    [0, 1, 0] : 0,
    [0, 1, 1] : 0,
    [1, 0, 0] : 1,
    [1, 0, 1] : 1,
    [1, 1, 0] : 1,
    [1, 1, 1] : 1
}

But when I run this it gives me the error: 但是当我运行它时,它给了我错误:

TypeError: unhashable type: 'list' TypeError:无法散列的类型:“列表”

How can I store lists in a dictionary? 如何将列表存储在字典中? I have the feeling that a list cannot be a key, but I want something like this, not a variable for each of the lists. 我感觉列表不能是键,但是我想要这样的东西,而不是每个列表的变量。

Keys in a dictionary have to be immutable. 字典中的键必须是不变的。 Lists are mutable, so they can't be keys. 列表是可变的,因此它们不能是键。 You can change them into tuples. 您可以将它们更改为元组。

You need at least tuples instead of list, so: 您至少需要元组而不是列表,因此:

data = {
    (0, 0, 0) : 0,
...
}

Note parenthesis, instead of square brackets. 注意括号,而不是方括号。 Tuples are like lists, except are immutable and can be used as keys in dictionary without a hassle. 元组就像列表一样,只是不可变的,并且可以轻松地用作字典中的键。

You can instead use tuples 您可以改为使用tuples

data = {
    (0, 0, 0) : 0,
    (0, 0, 1) : 0,
    (0, 1, 0) : 0,
    (0, 1, 1) : 0,
    (1, 0, 0) : 1,
    (1, 0, 1) : 1,
    (1, 1, 0) : 1,
    (1, 1, 1) : 1
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM