Explain Codes LogoExplain Codes Logo

How can I add new keys to a dictionary?

python
dictionary
update
key-management
Anton ShumikhinbyAnton Shumikhin·Aug 14, 2024
TLDR

Quickly insert a new key to your Python dictionary by calling upon dict[key] = value.

dict = {'a': 1, 'b': 2} dict['c'] = 3 print(dict) # Outputs: {'a': 1, 'b': 2, 'c': 3}

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:

dict.update({'d': 4}) # 'd' key is now part of our cool gang print(dict) # Outputs: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Adding multiple values and other dictionary operations

Multiplicity & dictionary merges

# Adding multiple key-value pairs: dict.update(e=5, f=6) # Inviting 'e' and 'f' to join our hangout print(dict) # Outputs: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6} # Merging two dictionaries (Python 3.9+): another_dict = {'g': 7, 'h': 8} # Meet our new friends 'g' and 'h' dict |= another_dict # Boom and they merged! print(dict) # Outputs: {'a': 1, 'b': 2, .... , 'g': 7, 'h': 8}

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.

dict['a'] = 'new value' # 'a' decided to reinvent itself print(dict['a']) # Outputs: 'new value'

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:

del dict['f'] # Farewell 'f', you will be missed value = dict.pop('c', None) # 'c' left us but also left a void, hence default None

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:

exists = 'key' in dict # If it does, you will know

Going through keys and values: Roll call!

To have an eagle's view of your dictionary contents, embark on an iteration adventure:

for key, value in dict.items(): # Let's take a roll call, shall we? print(f'{key}: {value}')

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:

keys = ['i', 'j'] values = [9, 10] paired_dict = dict(zip(keys, values)) # Union of keys and values, assemble!

Spring cleaning: Empty the dictionary

Feel the need for a fresh start? Don't worry, wipe the slate clean:

dict.clear() # Henceforth, a clean slate is granted!

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?

# Fast dict['k'] = 11 # Hustle done right # Slower dict.update({'k': 11}) # Like internet speed in the 90s