简体   繁体   English

Python:字典中的键也被视为变量吗?

[英]Python: are keys in dictionary also treated as variables?

I've just recently started learning programming in python as a beginner. 我刚刚刚开始学习python编程。 I was wondering: are keys in dictionary also treated as variables? 我想知道:字典中的键是否也被视为变量?

students = {"Jake": 12, "Rachel":12, "Ross":15}

the code contains the student names and their age. 该代码包含学生姓名及其年龄。 For example: Is "Jake" a variable that contains the value 12? 例如:“ Jake”是包含值12的变量吗? or is it treated as a variable? 还是将其视为变量?

While you can use a named value (or what you might think of as a 'variable') to construct a dictionary: 虽然可以使用命名值(或您可能认为的“变量”)构造字典:

>>> x=22
>>> di={x:x}
>>> di
{22: 22}

You can also demonstrate that the value of the named value (if that value is immutable) is used at the time of construction and not dynamic: 您还可以证明命名值的值(如果该值是不可变的)在构造时使用,并且不是动态的:

>>> x=5
>>> di
{22: 22}

The keys of a dict must be hashable (ie, unchanging; immutable) which would preclude the use of a list, set, or other named value that can change: 字典的必须是可散列的(即不变;不变),这将阻止使用可能会更改的列表,集合或其他命名值:

>>> changeable_list=[22]
>>> di={changeable_list:changeable_list}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

But the value of a dict can be dynamic and mutable: 但是dict的价值可以是动态且可变的:

>>> di={tuple(changeable_list):changeable_list}
>>> di
{(22,): [22]}

And that list can be modified: 该列表可以修改:

>>> changeable_list.append(44)
>>> changeable_list
[22, 44]
>>> di
{(22,): [22, 44]}

Notice how the value of the dict changes as the list changes because they are the same object. 注意dict的值如何随着列表的变化而变化,因为它们是同一对象。

As has been said, No, the keys of a dictionary are not variables. 如前所述,不,字典的键不是变量。 However, variables can sometimes key thought of as keys: 但是,有时可以将变量键认为是键:

students = {"Jake": 12, "Rachel":12, "Ross":15}

class Students:
    pass

s = Students()
s.Jake = 12
print(s.Jake, students['Jake'])

print(getattr(s, 'Jake'))

Output: 输出:

12 12
12

There is no syntax that I'm aware of that would allow you to access the value 12 from students in this form: students.Jake 我所知道的语法没有一种可以让您以这种形式从students访问值12students.Jake

However, modify the above code: 但是,修改上面的代码:

class Students:
    def __getitem__(self, key):
        return getattr(self, key)

... # as before
print(getattr(s, 'Jake'), s['Jake'])

Output: 输出:

12 12

Now students has an operator[] a little like a dictionary (Other operators might also be necessary.) 现在,学生有了一个类似于字典的操作符[](可能还需要其他操作符。)

So, an object can become like a dictionary because they have an underlying dictionary to make them work as objects. 因此,对象可以变得像字典一样,因为它们具有基础字典来使它们作为对象工作。

TL;DR - it depends on what you mean by a "variable". TL; DR-它取决于“变量”的含义。 dicts act like python namespaces but allow more types of variable names. dict的行为类似于python命名空间,但允许更多类型的变量名。

Python objects have no inherent name. Python对象没有固有名称。 They can be referenced by one or more other objects and when their reference count goes to zero, they are deleted. 它们可以被一个或多个其他对象引用,并且当它们的引用计数变为零时,它们将被删除。 When you assign an object to a variable, some data structure adds a reference to the the object and associates that object with the name. 当您将对象分配给变量时,某些数据结构会对该对象添加一个引用,并将该对象与名称相关联。 That data structure is the variable's namespace (that is, the context where the variable name is valid). 该数据结构是变量的名称空间(即变量名有效的上下文)。 And for most objects, that data structure is a dict . 对于大多数对象而言,该数据结构是一个dict

Lets look at two examples: 让我们看两个例子:

class Students:
    pass

student_obj = Students()

and

student_dct = {}

I could treat Jake as aa variable 我可以把杰克当作一个变量

>>> student_obj.Jake = 12
>>> student_obj.Jake
12
>>> student_obj.__dict__
{'Jake': 12}

Or add it to the dict 或将其添加到字典

>>> student_dct["Jake"] = 12
>>> student_dct["Jake"]
12
>>> student_dct
{'Jake': 12}

That's really close to the first example! 那真的很接近第一个例子! The advantage to a variable is that it is parsed by python and python does the lookup for you. 变量的优点是它是由python解析的,而python会为您查找。 Python turns student_obj.Jake into student_obj.__getattribute__("Jake") . Python将student_obj.Jake转换为student_obj.__getattribute__("Jake") For normal class objects, python will check the object __dict__ for the name then fall back to containing namespaces. 对于普通的类对象,python将检查对象__dict__的名称,然后回退到包含名称空间的名称。 Classes that use __slots__ or are implemented in C follow different rules. 使用__slots__或在C中实现的类遵循不同的规则。

But variable assignment is a disadvantage if you want to use names that don't fit python's sytax rules. 但是,如果您要使用不符合python语法规则的名称,则变量分配是不利的。

>>> student_obj.Jim Bob = 12
  File "<stdin>", line 1
    student_obj.Jim Bob = 12
                      ^
SyntaxError: invalid syntax

Here, you want "Jim Bob" to be a variable but it can't be used directly as a variable because it breaks python. 在这里,您希望“ Jim Bob”是一个变量,但由于它破坏了python,因此不能直接用作变量。 So, you put it into a dict 因此,您将其放入字典中

>>> student_dct["Jim Bob"] = 12

So, dictionary items are "variables" (the value can be referenced and reassigned) but are not "python variables" because python doesn't implement the lookup for you. 因此,字典项是“变量”(可以引用并重新分配值),但不是“ python变量”,因为python不会为您实现查找。

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

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