Skip to content
Advertisement

Why I can’t add more keys to a dict? – Python

I have a program where I want to add more keys to a dictionary.

When I add only one key, everything is OK:

dict = {}
dict["key1"] = "Value"
print(dict)

//{'key1':'value'}

But when I add a second key, I get an error message:

dict = {}
dict["key1"]["key2"] = "Value"
print(dict)

//Traceback (most recent call last):
  File "***", line 2, in <module>
    dict["key1"]["key2"] = "value"
  KeyError: 'key1'

How can I add more keys?

Advertisement

Answer

dict['key1'] = {'key2': 'value'}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement