2017-10-02 6 views
0

ここにコードがあります。なぜdict ['port_password'] ['server_port'] = 126がこの場合inPyhtonで正しいのですか?

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

コンフィグ[ 'port_password'] = {}、なぜ設定[ 'port_password'] [ 'SERVER_PORT'] = 126は、正しいですか?

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

私が最初の行をコメントアウトすると、「name 'config'は定義されていません」.why?ここで

+2

最初の行は辞書オブジェクトを作成し、次の2行は_modify_です。最初の行をコメントアウトすると、辞書は決して作成されないので、変更する必要はありません。 –

+0

最初の行に126を置くだけで、2番目と3番目が無意味です –

答えて

2

は、アノテーションを使用してコードです:あなたがこれを行う場合は

# 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) 
+1

非常に簡潔です!話題以外の話題:私はあなたにとりわけRE:並行性を与えた話をYouTubeに載せています。すべての素晴らしいコンテンツをありがとう! –

0

config = {'port_password':{'server_port':123}} 

をあなたは新しい辞書configを定義するので、この名前が存在する、としてますが、キーport_passwordを設定しました値{'server_port': 123}

この行を削除すると、config変数は定義されておらず、NameErrorになります。

しかし、次の行に、あなたが書いた:

config['port_password'] = {} 

ので、キーport_passwordに関連付けられている値は、空の辞書です。

あなたが書いた:

config['port_password']['server_port'] = 126 

あなたはこの空の辞書を充填しています。キーを値126で設定します。

関連する問題