5 Best Ways to Add a Key-Value Pair to a Dictionary in Python

πŸ’‘ Problem Formulation: How do you add a new key-value pair to an existing dictionary in Python? Suppose you have a dictionary {"apple": 1, "banana": 2} and you want to insert a new key-value pair {"cherry": 3} such that the updated dictionary becomes {"apple": 1, "banana": 2, "cherry": 3}. This article explores five effective methods to achieve this.

Method 1: Using Subscript Syntax

The subscript syntax is the simplest method to add a key-value pair to a Python dictionary. It involves using the square brackets to assign a value to a key directly on the dictionary object. When using this method, if the key already exists in the dictionary, its value will be updated; if it does not exist, the key-value pair will be added.

Here’s an example:

fruit_prices = {"apple": 1, "banana": 2}
fruit_prices["cherry"] = 3

Output:

{"apple": 1, "banana": 2, "cherry": 3}

This code snippet directly assigns the value 3 to a new key "cherry" in the fruit_prices dictionary. As “cherry” wasn’t previously a key in the dictionary, it is added along with its associated value.

Method 2: Using the update() Method

The update() method is a built-in function of a Python dictionary that updates the dictionary with elements from another dictionary object or an iterable of key-value pairs. It is particularly useful when adding multiple key-value pairs at once.

Here’s an example:

fruit_prices = {"apple": 1, "banana": 2}
fruit_prices.update({"cherry": 3})

Output:

{"apple": 1, "banana": 2, "cherry": 3}

This snippet uses the update() method to add the key-value pair {"cherry": 3} to the fruit_prices dictionary. If “cherry” was already present, its value would be updated to 3.

Method 3: Using the setdefault() Method

The setdefault() method gets the value of a key in a dictionary if it is present. If it is not, it inserts the key with a specified default value. This is useful for initializing default values while also potentially adding a new key.

Here’s an example:

fruit_prices = {"apple": 1, "banana": 2}
fruit_prices.setdefault("cherry", 3)

Output:

{"apple": 1, "banana": 2, "cherry": 3}

In this code, setdefault() is used to set the default value 3 for the key "cherry" which does not exist in the fruit_prices dictionary. Consequently, this key-value pair is added to the dictionary.

Method 4: Using Dictionary Unpacking

Dictionary unpacking uses the ** operator to merge the contents of two dictionaries. This method is useful if you want to create a new dictionary by combining an existing dictionary with additional key-value pairs.

Here’s an example:

fruit_prices = {"apple": 1, "banana": 2}
new_entry = {"cherry": 3}
fruit_prices = {**fruit_prices, **new_entry}

Output:

{"apple": 1, "banana": 2, "cherry": 3}

This code creates a new dictionary that merges fruit_prices with new_entry. The ** operator is used to unpack the key-value pairs from both dictionaries into a new dictionary object that has all elements from both.

Bonus One-Liner Method 5: Using a Comprehension

You can use a dictionary comprehension to conditionally add key-value pairs to a dictionary. This method is suitable when the decision to add a key-value pair depends on some condition.

Here’s an example:

fruit_prices = {"apple": 1, "banana": 2}
fruit_prices = {k: v for k, v in [(k, v) for k, v in fruit_prices.items()] + [("cherry", 3)]}

Output:

{"apple": 1, "banana": 2, "cherry": 3}

This code utilizes a dictionary comprehension in combination with list concatenation to add the ("cherry", 3) pair to the fruit_prices dictionary. The comprehension iterates over the items of the existing dictionary and the newly added list, creating a new dictionary with all the key-value pairs.

Summary/Discussion

  • Method 1: Subscript Syntax. Simple and straightforward. Can only add one key-value at a time.
  • Method 2: update() Method. Can add multiple key-value pairs at once. Overwrites existing keys.
  • Method 3: setdefault() Method. Adds a key with a default value if it doesn’t exist. Leaves existing keys unchanged.
  • Method 4: Dictionary Unpacking. Useful for merging dictionaries. Creates a new dictionary instead of modifying in place.
  • Method 5: Comprehension. Offers conditional addition and is a one-liner, but can be less readable for complex conditions.