How can I add new keys to a dictionary?

Explanation

If you want to add new keys to a dictionary you have to create a new key/value pair on a dictionary. And you can do this by assigning a value to that key.

d = {'key': 'value'}
print(d)  # {'key': 'value'}

d['mynewkey'] = 'mynewvalue'

print(d)  # {'key': 'value', 'mynewkey': 'mynewvalue'}

And if the key does not exist, it will then be added and points to that value. So if it exists, the current value it points to is overwritten. After that, it will become a new pair.

 

Also, read How can I check for an empty/null string in JavaScript?

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *