简体   繁体   中英

Python, extracting dictionary values

I'm trying to extract some values from a dictionary object and assign it to a local variable. 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:

>>> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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