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

时间:2018-05-06 16:53:20

标签: python python-3.x dictionary

我刚刚开始在python中学习编程作为初学者。我想知道:字典中的键也被视为变量吗?

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

代码包含学生姓名及其年龄。 例如:“Jake”是一个包含值12的变量吗?或者它被视为变量?

3 个答案:

答案 0 :(得分:1)

While you can use a named value (or what you might think of as a 'variable') to construct a dictionary:

sudo docker run -d -p 9090:8080 -p 8888:80 --network public --name traefik -v $PWD/traefik.toml:/etc/traefik/traefik.toml -v /var/run/docker.sock:/var/run/docker.sock traefik

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:

 stage ('Postgres: despliegue inicial de la base de datos') {
            def dbImage = docker.build("catalogador/catalogador-tfg-db:${BRANCH_NAME}","--label jenkins ./database")
            dbHostname = "${BRANCH_NAME}-${BUILD_NUMBER}-db"
            db = dbImage.run("-p 5432:5432 --network public --name ${dbHostname}")
            timeout(time: 3, unit: 'MINUTES') {
                sh "until [ \$(docker logs ${dbHostname} --tail 50 2>&1 | grep 'init process complete' | wc -l) -gt 0 ]; do sleep 10; done"
            }

        }

        stage ('Tomcat: despliegue de la aplicación') {
            def webImage = docker.build("asd/asd-tfg-app:${BRANCH_NAME}","--label jenkins ./appserver")
            def webJavaOpts = "-Dspring.datasource.url=jdbc:postgresql://${dbHostname}:5432/${dbName} " +
                    "-Dspring.datasource.username=${dbUser} " +
                    "-Dspring.datasource.password=${dbPassword} "
            webHostname = "${BRANCH_NAME}-${BUILD_NUMBER}-app"
            def proxyOpts = "-l 'traefik.frontend.rule=Host:${testingDomainName};PathPrefixStrip:/${webProxyPrefixPath}' " +
                    "-l 'traefik.port=9090'"
            web = webImage.run("-p 9999:8080 -p 9898:80 --network public --link ${dbHostname} --name ${webHostname} -e JAVA_OPTS='${webJavaOpts}' ${proxyOpts}")
            timeout(time: 3, unit: 'MINUTES') {
                sh "until [ \$(docker logs ${webHostname} --tail 50 2>&1 | grep 'Server startup' | wc -l) -gt 0 ]; do sleep 10; done"
            }
        } 

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:

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

But the value of a dict can be dynamic and mutable:

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

And that list can be modified:

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

Notice how the value of the dict changes as the list changes because they are the same object.

答案 1 :(得分:0)

As has been said, No, the keys of a dictionary are not variables. However, variables can sometimes key thought of as keys:

console.log

Output:

valueOf

There is no syntax that I'm aware of that would allow you to access the value students = {"Jake": 12, "Rachel":12, "Ross":15} class Students: pass s = Students() s.Jake = 12 print(s.Jake, students['Jake']) print(getattr(s, 'Jake')) from 12 12 12 in this form: 12

However, modify the above code:

students

Output:

students.Jake

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.

答案 2 :(得分:0)

TL; DR - 它取决于“变量”的含义。 dicts就像python命名空间一样,但允许更多类型的变量名称。

Python对象没有固有名称。它们可以被一个或多个其他对象引用,当它们的引用计数变为零时,它们将被删除。将对象分配给变量时,某些数据结构会添加对该对象的引用,并将该对象与名称相关联。该数据结构是变量的名称空间(即变量名称有效的上下文)。对于大多数对象,该数据结构是dict

让我们看两个例子:

class Students:
    pass

student_obj = Students()

student_dct = {}

我可以将杰克视为变量

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

或将其添加到词典

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

这与第一个例子非常接近!变量的优点是它由python解析,python为你查找。 Python将student_obj.Jake转换为student_obj.__getattribute__("Jake")。对于普通的类对象,python将检查对象__dict__的名称,然后回退到包含名称空间。使用__slots__或在C中实现的类遵循不同的规则。

但是如果要使用不符合python的sytax规则的名称,则变量赋值是一个缺点。

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

在这里,你希望“Jim Bob”是一个变量,但它不能直接用作变量,因为它会破坏python。所以,你把它放入一个词典

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

因此,字典项是“变量”(值可以被引用和重新分配)但不是“python变量”,因为python没有为你实现查找。