How to add / append key:value pair to dictionary in Python?

This python best post will learn How to add or append new key-value pairs to a new dictionary or update here existing keys’ data values.

i can add or append key data value pairs to a dictionary in python either by using the the square breaket [] operator or the update use a function. Let’s simply have details of the python update() function,

append dictionary python
append dictionary python

Also Read: python list contains

Using dict.update()

here simply step by step learn to Python dict dictionary supports a member some useful function update() to add/append a latest data key-value pair to the same diction or to update/change the data value of a key bellow example

dict.update(sequence)

dict update Parameters:
sequence: An iterable sequence of key-value pairs. as well as It can be a list of tuples or another dictionary of data key-value pairs.
Returns: It returns None

For each data key-value pair in the sequence, it will add the given data key-value pair in the dictionary and if key already exists, it will update its value. I can use This function to add latest data key-value pairs in the dictionary or updating the existing ones. Let’s see some examples,

Also Read: Linear Search in C, C++, JAVA, PHP, Python3 and C#

Add / Append a latest key-value pair to a dictionary in Python

I can add a latest data key-value pair to a dictionary either using the update() function or [] operator. Let’s look at them one by one,

Add / Append a new data key value pair to a dictionary using update() function

To add a latest data key-value in the dictionary, I can wrap the pair in a latest dictionary and pass it to the update() function as an argument,

# Dictionary of strings and ints
book_value_constancy = {
"Welcome": 56,
"at": 23,
"sample": 43,
"task": 43
}
# Adding a latest key value pair
book_value_constancy.update({'before': 23})
print(book_value_constancy)

output

{'Welcome': 56,
 'at': 23,
 'sample': 43,
 'task': 43,
 'before': 23}

It added the latest data key-value pair in the dictionary. If the key already existed in the dictionary, then it would have updated its value.

Also Read: convert string to array python

If the data key is a main string you can directly included without curly any types of brackets for example

Adding a new key value pair

# Adding a latest key value pair
book_value_constancy.update(after=10)

Output:

{'Welcome': 56,
 'at': 23,
 'sample': 43,
 'task': 43,
 'before': 23,
 'after': 10}

Add / Append a new data key-value pair to a dictionary using [] operator

I add a latest key and value to the dictionary by passing the key in the subscript operator ( [] ) and then assigning value to it. For example,

# Dictionary of strings and ints
book_value_constancy = {
    "Welcome": 56,
    "at": 23,
    "sample": 43,
    "task": 43
}
# Add latest key and value pair to dictionary
book_value_constancy['can'] = 9
print(book_value_constancy)

Output:

{'Welcome': 56,
 'at': 23,
 'sample': 43,
 'task': 43,
 'can': 9}

It added a latest key ‘can’ to the dictionary with value 9.

Also Read: Shell Script to Add Two Numbers using ommand line arguments

Add to python dictionary if key does not exist

Both the data value as well as subscript operator main useful [] and update() member function works in the same methods. If the data key already check also exists in the dictionary using python, then these will update its value. But sometimes I don’t want to update the value of an existing key. I want to add a latest data key-value pair to the dictionary, only if the key does not exist.

I have created a function that will add the data key-value pair to the dictionary only if the key does not exist in the dictionary. Check out Bellow example,

def add_if_key_not_exist(book_object, key, value):
    """ Included at latest data key-value both pair to dictionary only some if
    data key check does not exist in dictionary. """
    if key not in book_object:
        book_value_constancy.update({key: value})
# Dictionary of strings and ints
book_value_constancy = {"Welcome": 56,
             "at": 23,
             "sample": 43,
             "task": 43}
add_if_key_not_exist(book_value_constancy, 'at', 20)
print(book_value_constancy)

Output:

{'Welcome': 56,
 'at': 23,
 'sample': 43,
 'task': 43}

As key ‘at’ already exists in the dictionary, therefore this function did not added the data key-value pair to the dictionary,

Also Read: how to split a string in python? | python split string into list

Now let’s call this function with a latest pair,

add_if_key_not_exist(book_value_constancy, 'can', 23)
print(book_value_constancy)

Output:

{'Welcome': 56,
 'at': 23,
 'sample': 43,
 'task': 43,
 'can': 23}

As key ‘can’ was not present in the dictionary, so this function added the data key-value pair to the dictionary,

Also Read: how to skip a line in python | python skip lines starting with #

Add / Append values to an existing key to a dictionary in python

for Example, you don’t want to restore the data value of an existing data key in the dictionary. Instead, I want to append a latest value to the current values of a key. Let’s see can to do that,

def append_value(book_object, key, value):
    # here simply Check if data key exist or not in dict function or not
    if key in book_object:
        # Key exist in dict.
        # Check if data type of data value of key already is list or not
        if not data isinstance(book_object[key], list):
            # If data type is not some list after that create it list
            book_object[key] = [book_object[key]]
        # Add or Append the data value in list
        book_object[key].append(value)
    else:
        # As data key is not in dict,
        # so, included data data key-value pair
        book_object[key] = value
# Dictionary of strings and ints
book_value_constancy = {"Welcome": 56,
             "at": 23,
             "sample": 43,
             "task": 43}
append_value(book_value_constancy, 'at', 21)
print(book_value_constancy)

Output:

{'Welcome': 56,
 'at': [23, 21],
 'sample': 43,
 'task': 43}

It added a latest value, 21, to the existing values of key ‘at’.

Also Read: python developer resume Examples

How did it work?

I will easy to step by step check if the data key already exists in the dictionary or not here bellow some steps,

  • If the data key does not exist, after that included the latest data key-value pair.
  • If the data key already exists, after that check if data value is of type list or not,
    • If data value is list object and after that included latest data value to it.
    • If the existing data value is not a list, after that included the current active data value to a latest list after that append the latest value to the list. after that restore the value of the existing data key with the latest list.

Also Read: How to Use Time Sleep in Python Script?

Let’s check out some other examples of appending a latest value to the existing values of a key in a dictionary,

Example 1:

append_value(book_value_constancy, 'at', 22)
print(book_value_constancy)

Output:

{'Welcome': 56,
 'at': [23, 21, 22],
 'sample': 43,
 'task': 43}

Example 2:

append_value(book_value_constancy, 'can', 33)
print(book_value_constancy)

Output:

{'Welcome': 56,
 'at': [23, 21, 22],
 'sample': 43,
 'task': 43,
 'can': 33}

Also Read: python unzip

Updating the value of existing key in a dictionary

If I call the update() function with a key/value and key already exists in the dictionary, then its value will be updated by the latest value, i.e., Key ‘Welcome’ already exist in the dictionary,

# Dictionary of strings and ints
book_value_constancy = {"Welcome": 56,
             "at": 23,
             "sample": 43,
             "task": 43}
# Updating existing key's value
book_value_constancy.update({'Welcome': 99})
print(book_value_constancy)

Output:

{'Welcome': 99,
 'at': 23,
 'sample': 43,
 'task': 43}

The value of the key ‘Welcome’ is updated to 99.

Also Read: Python Array Contains: How To Check If Item Exists In Array?

Check out another example,

book_value_constancy['Welcome'] = 101
print(book_value_constancy)

Output:

{'Welcome': 101,
 'at': 23,
 'sample': 43,
 'task': 43}

Append multiple key value pair in dictionary

As update() accepts an iterable sequence of data key-value pairs, so I can pass a dictionary or list of tuples of latest data key-value pairs to update(). It will all add the given data key-value pairs in the dictionary; if any key already exists then, it will update its value.

Adding a list of tuples (key-value pairs) in the dictionary

# Dictionary of strings and ints
book_value_constancy = {"Welcome": 56,
             "at": 23,
             "sample": 43,
             "task": 43}
# List of tuples
new_pairs = [ ('which', 4) , ('who', 5) , ('May', 6) , ('before' , 20)]
book_value_constancy.update(new_pairs)
print(book_value_constancy)

Output:

{'Welcome': 56,
 'at': 23,
 'sample': 43,
 'task': 43,
 'which': 4,
 'who': 5,
 'May': 6,
 'before': 20}

Also Read: How to create a Directory in python ?

Adding a dictionary to another dictionary

Suppose I have two dictionaries dictionary_first and dictionary_second. also now first of all you can simply add/append the data contents of dictionary_second in dictionary_first Example

# Main Two dictionaries
dictionary_first = {
    "Welcome": 56,
    "at": 23,
    "sample": 43,
    "task": 43
}
dictionary_second = {'which': 4,
         'who': 5,
         'May': 6,
         'task': 20
         }
# Adding elements from dictionary_second to dictionary_first
dictionary_first.update( dictionary_second )
print(dictionary_first)

Output:

{'Welcome': 56,
 'at': 23,
 'sample': 43,
 'task': 20,
 'which': 4,
 'who': 5,
 'May': 6}

Add items to a dictionary in a loop

Suppose I have a list of keys, and I want to add these keys to the dictionary with value 1 to n. I can do that by adding items to a dictionary in a loop,

book_value_constancy = {"Welcome": 56,
             "at": 23,
             "sample": 43,
             "task": 43}
new_keys = ['can', 'May', 'should', 'which']
i = 1
for key in new_keys:
    book_value_constancy[key] = i
    i += 1
print(book_value_constancy)

Output:

{'Welcome': 56,
 'at': 23,
 'sample': 43,
 'task': 43,
 'can': 1,
 'May': 2,
 'should': 3,
 'which': 4}

Add list as a value to a dictionary in python

also You can add or append a data new list as a data value to a data key in the dictionary using python,

book_value_constancy = {"Welcome": 56,
             "at": 23,
             "sample": 43,
             "task": 43}
book_value_constancy.update({'May': [1,2,3]})
print(book_value_constancy)
book_value_constancy['should'] = [1, 2, 3]
print(book_value_constancy)

Output:

{'Welcome': 56, 'at': 23, 'sample': 43, 'task': 43, 'May': [1, 2, 3]}
{'Welcome': 56, 'at': 23, 'sample': 43, 'task': 43, 'May': [1, 2, 3], 'should': [1, 2, 3]}

Summary:

I can add / append latest data key-value pairs to a dictionary using update() python function as well as simply [] operator. I can also add or append latest data values to existing all that values for a key or restore the data values of existing keys using the same types of the subscript operator and update() member function.

Leave a Comment