简体   繁体   English

Python,提取字典值

[英]Python, extracting dictionary values

I'm trying to extract some values from a dictionary object and assign it to a local variable.我正在尝试从字典 object 中提取一些值并将其分配给局部变量。 See this:看到这个:

FTP_INFO = {'DATA': {'host': 'ftp.host.com',
                     'user': 'user',
                     'pass': 'password',
                     'path': '/home/user'}}

Then I try this:然后我试试这个:

v_host = FTP_INFO['DATA']['host']
print("HOST: ", v_host)

And I get this:我明白了:

print("HOST: ", v_host)

NameError: name 'v_host' is not defined

Yet, this works fine:然而,这工作正常:

print("HERE: " + FTP_INFO['DATA']['host'])

Am I missing something?我错过了什么吗?

I pasted this exact code (which as best as I can tell from your question is what you're running):我粘贴了这个确切的代码(我从你的问题中可以看出你正在运行的是什么):

FTP_INFO = {'DATA': {'host': 'ftp.host.com',
                     'user': 'user',
                     'pass': 'password',
                     'path': '/home/user'}}
v_host = FTP_INFO['DATA']['host']
print("HOST: ", v_host)

into a Python interpreter and got this output:进入 Python 解释器并得到这个 output:

>>> FTP_INFO = {'DATA': {'host': 'ftp.host.com',
...                      'user': 'user',
...                      'pass': 'password',
...                      'path': '/home/user'}}
>>> v_host = FTP_INFO['DATA']['host']
>>> print("HOST: ", v_host)
HOST:  ftp.host.com

So this works fine.所以这很好用。 When you can find the difference between the code you're actually running and the code that I pasted above, you'll hopefully have the answer to why it's not working.当您发现您实际运行的代码与我上面粘贴的代码之间的区别时,您就有希望找到为什么它不起作用的答案。

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

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