How can I add new keys to a dictionary?
Quickly insert a new key to your Python dictionary by calling upon dict[key] = value
.
Dissect the above statement: Key-value pairs get injected as you assign new pairs to your dictionary! Voila!
Added details: Update one or more keys
You can use the update()
function to amend an existing key or even add one more:
Adding multiple values and other dictionary operations
Multiplicity & dictionary merges
Keep in mind: Starting Python 3.9, you can be neater by using dict1 |= dict2
instead of heavy-lifting with dict1.update(dict2)
.
Overwriting: There can only be one
If you think a key is a Highlander, think again. A key in a dictionary is unique. Assigning a value to an already existing key merely replaces the original.
Removing keys: Goodbye my lover, goodbye my friend
To rid a key and its linked value, banish it with either the del
keyword or pop()
method's wand:
More, more, more: Additional tools for your Python toolbox
Verifying a key's existence: I see dead people
Before meddling with keys, ensure they exist:
Going through keys and values: Roll call!
To have an eagle's view of your dictionary contents, embark on an iteration adventure:
Assembling dictionaries from sequences: Assemble!
If you have two lists, one hustling keys and the other bamboozling with corresponding values, join them with the power of zip:
Spring cleaning: Empty the dictionary
Feel the need for a fresh start? Don't worry, wipe the slate clean:
Adding keys: Direct assignment for the win
Truth be told, direct assignment is much faster than update()
. We all love things done in a jiffy, don't we?
Was this article helpful?