Can you add values to a dictionary in python?

Can you add values to a dictionary in python?

Python dictionary has a key-value pair data structure which means if you want to add value to the dictionary, there should be a key for that value. It is possible to add a new element as a key-value after the dictionary has been created. There are many ways that you can use to add values to a dictionary, and we will see each approach one by one in this tutorial.

To add values to a Python dictionary, use one of the following approaches.

  1. Assigning a value to a new key.
  2. Using dict.update() method to add multiple key-values.
  3. For Python 3.9+, use the merge operator ( | ).
  4. For Python 3.9+, use the update operator ( |= ).
  5. Creating a custom function.
  6. Using __setitem__() method (It is not recommended).

Assigning a value to a new key in Dictionary

To create an empty dictionary in Python, use the { } and assign it to a variable.

et_dict = {}
print(et_dict)

Output

{}

To create a dictionary with initial values in Python, use one of the following approaches.

init_dict = {'a': 11, 'b': 21, 'c': 19}
print(init_dict)

init_dict_second = dict(a=11, b=21, c=19)
print(init_dict_second)

init_dict_third = {k: v for k, v in (('a', 11), ('b', 21), ('c', 19))}
print(init_dict_third)

Output

{'a': 11, 'b': 21, 'c': 19}
{'a': 11, 'b': 21, 'c': 19}
{'a': 11, 'b': 21, 'c': 19}

You can see that we have seen three different approaches to define a dictionary with initial values.

Now, let’s append values to a dictionary by assigning a value to that key. The new value has a key name “d” and its value is 46.

init_dict['d'] = 46

This means that we are appending a new key-value pair to an existing dictionary.

See the complete code.

init_dict = {'a': 11, 'b': 21, 'c': 19}
print(init_dict)

print("Add new value to a dict")
init_dict['d'] = 46
print(init_dict)

Output

{'a': 11, 'b': 21, 'c': 19}
Add new value to a dict
{'a': 11, 'b': 21, 'c': 19, 'd': 46}

If the key doesn’t exist, it’s added and points to that value. If it exists, the current value it points to is overwritten. This approach of adding value to an existing dictionary is highly recommended.

Using dict.update() method

Python dict.update() is a built-in method that updates one dictionary with the elements of another dictionary object or from an iterable value of key pair.

To add multiple keys simultaneously in Python, use dict.update() method.

init_dict = {'a': 11, 'b': 21, 'c': 19}
print(init_dict)

new_values = {'d': 18, 'e': 46, 'f': 29}
print("Adding multiple values to a dict")
init_dict.update(new_values)
print(init_dict)

Output

{'a': 11, 'b': 21, 'c': 19}
Adding multiple values to a dict
{'a': 11, 'b': 21, 'c': 19, 'd': 18, 'e': 46, 'f': 29}

Using the merge operator ( | ) in Python 3.9

Python 3.9 comes with a merge operator that helps us merging the dictionaries. The Merge (|) operator has been added to a built-in dict class. You use the merge operator to combine two dictionaries or, in other words, create a new dictionary by adding new key-values to the existing dictionary.

init_dict = {'a': 11, 'b': 21, 'c': 19}
print(init_dict)

new_values = {'d': 18, 'e': 46, 'f': 29}
print("Merging dictionary values using merge operator")
final_dict = init_dict | new_values
print(final_dict)

Output

{'a': 11, 'b': 21, 'c': 19}
Adding multiple values to a dict
{'a': 11, 'b': 21, 'c': 19, 'd': 18, 'e': 46, 'f': 29}

You can see that we got the combined dictionary with updated values.

Using the update operator ( |= ) in Python 3.9

Python 3.9 comes with one more operator called the update operator. The update (|=) operator has been added to the built-in dict class. The update (|=) operator returns the left operand merged with the right operand.

init_dict = {'a': 11, 'b': 21, 'c': 19}
print(init_dict)

new_values = {'d': 18, 'e': 46, 'f': 29}
print("Adding dictionary values using update operator")
init_dict |= new_values
print(init_dict)

Output

{'a': 11, 'b': 21, 'c': 19}
Updating dictionary values using update operator
{'a': 11, 'b': 21, 'c': 19, 'd': 18, 'e': 46, 'f': 29}

We add multiple values to the existing dictionary using the |= operator, and it won’t work below Python 3.9 version.

Creating a custom function

If you want to create a custom function that will do the job of adding the values to the dictionary, you can do that. Let’s see the following code.

class create_dict(dict):

    def __init__(self):
        self = dict()

    def add(self, key, value):
        self[key] = value

# example


dct = create_dict()
dct.add('a', 19)
dct.add('b', 21)
print(dct)

Output

{'a': 19, 'b': 21}

There’s another way of adding new values to a dict that you shouldn’t use, and that is the use of the __setitem__ method. The main reason behind this is that the methods that start with __ are private use by Python itself. So it is a good practice not to use the private method of Python.

dct = {}
dct.__setitem__('a', 21)
print(dct)

Output

{'a': 21}

We have added a value to an empty dictionary using the __setitem__() method. Again this approach is not recommended, and I advise you to follow the first or second approach of this tutorial.

That is it for this tutorial.

How can you insert values in to dictionary?

Let's see how can we add new keys to a dictionary using different ways to a dictionary..
Create a dictionary first..
Method 1: Add new keys using the Subscript notation..
Method 2: Add new keys using update() method..
Method 3: Add new keys using the __setitem__ method..
Method 4: Add new keys using the ** operator..

How do you add an item to a dictionary in Python?

Update Dictionary The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added. The argument must be a dictionary, or an iterable object with key:value pairs.

Can I add multiple values to dictionary Python?

By using the dictionary. update() function, we can easily append the multiple values in the existing dictionary. In Python, the dictionary. update() method will help the user to update the dictionary elements or if it is not present in the dictionary then it will insert the key-value pair.

Can we add only values to a dictionary?

Whilst the values of a dictionary can be of any type, the keys must be immutable such as strings, numbers, or tuples. What is this? In terms of syntax, a dictionary is defined by enclosing a comma-separated list of key-value pairs in curly brackets( i.e. { } ).