zhan zhan - 3 years ago 212
Python Question

why dict['port_password']['server_port'] = 126 is correct in this case inPyhton?

Here is the code.

config={'port_password':{'server_port':123}}
config['port_password'] = {}
config['port_password']['server_port'] = 126
print(config)


config['port_password'] = {},why does config['port_password']['server_port'] = 126 is correct?

#config={'port_password':{'server_port':123}}
config['port_password'] = {}
config['port_password']['server_port'] = 126
print(config)


when i comment out the first line,it said:"name 'config' is not defined".why?

Answer Source

Here is your code with annotations:

# define a variable "config" referring to a dictionary with one key
# and whose value is another dictionary
config={'port_password':{'server_port':123}}

# lookup the "config" variable and replace its inner dictionary
# with an inner dictionary
config['port_password'] = {}

# look the "config" variable giving a dictionary, then lookup
# "port_password" in that dictionary, giving the inner empty dict
# and set "server_port" to 126 in that inner dict
config['port_password']['server_port'] = 126

# lookup the "config" variable and display the nested dictionaries
print(config)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download