Explain Codes LogoExplain Codes Logo

Add a new item to a dictionary in Python

python
dictionary
data-structures
best-practices
Anton ShumikhinbyAnton Shumikhin·Nov 7, 2024
TLDR

To insert an item into a dictionary in Python, assign a value to a new key:

my_dict['new_key'] = 'new_value'

To merge a dictionary into another one, use the .update() method:

my_dict.update({'next_key': 'next_value'})

These ways are speedy and adaptable, perfect for expanding your dictionary.

Adding a single item

When you need to add just one item, you can do this directly. Remember, if 'new_key' isn't in the dictionary, it will be added while if it is, the existing value will be updated:

my_dict['new_key'] = 'new_value' # as easy as pie!

Be cautious about overwriting an existing value. You might want to first check if the key exists:

if my_dict.get('new_key') is None: my_dict['new_key'] = 'new_value' # a precaution is worth a thousand keys!

Batch item insertion

For inserting several items at once, the .update() method is your knight. Whether it's merging dictionaries, chaining updates, or using dictionary unpacking, .update() is one method to rule them all:

my_dict.update(another_dict) # The dictionaries unite! my_dict.update(key1=value1, key2=value2) # And they shall be one... my_dict.update({**dict1, **dict2}) # Unleash the power of dictionary unpacking!

Efficiency matters

Direct assignment is your efficiency champion for single additions. For multiple additions, .update() stays resource-efficient as it modifies the existing dictionary without conjuring new ones.

Avoid tempting but wrong directions such as + operator — it's for mathematical operations not for dictionaries!

Advanced manipulations

Let's notch up the difficulty level. Here are some advanced strategies for maximising control and making more code-efficient manipulations:

Drop it like it's hot! (Conditional updates)

Just like DJ Snake and Lil'Jon, Python's got the beat for conditional updates.

# Turn down for what? (if new_key isn't in the dictionary) my_dict['new_key'] = 'new_value' if 'new_key' not in my_dict else my_dict['new_key']

Loop it up! (Iterative addition)

Got an iterable to add? Fire up a loop, and lean back!

keys = ['key1', 'key2'] values = ['value1', 'value2'] for k, v in zip(keys, values): my_dict[k] = v # map it like you mean it!

The Safe House (setdefault)

The setdefault method only changes values to keys if the key doesn't exist:

my_dict.setdefault('new_key', 'new_value')

setdefault is sure-shot safe but lacks the charm for batch updates.

Oh-oh! (Exception handling)

You might stumble upon a key error while adding to a dict. Aim for a smooth execution using try-except blocks:

try: my_dict['new_key'] = 'new_value' except KeyError: # Here is where I'd put my error-handling code... if I had one!