Tutorial

How to Add and Update Python Dictionaries Easily

Updated on December 16, 2024
How to Add and Update Python Dictionaries Easily

Introduction

A dictionary is a built-in Python data type. It is a sequence of key-value pairs, where each key is unique and maps to a value. Dictionaries are mutable objects, meaning you can change their content without changing their identity. However, dictionary keys are immutable and need to be unique within each dictionary. This makes dictionaries highly efficient for lookups, insertions, and deletions.

Dictionaries are widely used in Python for various applications such as counting occurrences, grouping data, and storing configurations. Despite their versatility, there’s no built-in add method for dictionaries. Instead, there are several ways to add to and update a dictionary, each with its own use case and advantages.

In this article, you’ll learn different methods to add to and update Python dictionaries. You’ll learn how to use the Python assignment operator, the update() method, and the merge and update dictionary operators. By the end of this tutorial, you’ll have a solid understanding of how to manage and manipulate dictionaries effectively in your Python programs.

Deploy your Python applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.

Four Methods to Add to the Python Dictionary

  1. Using the Assignment Operator
  2. Using the Update Method
  3. Using the Merge Operator
  4. Using the Update Operator

Add to Python Dictionary Using the = Assignment Operator

You can use the = assignment operator to add a new key to a dictionary:

dict[key] = value

If a key already exists in the dictionary, then the assignment operator updates, or overwrites, the value.

The following example demonstrates how to create a new dictionary and then use the assignment operator = to update a value and add key-value pairs:

dict_example = {'a': 1, 'b': 2}

print("original dictionary: ", dict_example)

dict_example['a'] = 100  # existing key, overwrite
dict_example['c'] = 3  # new key, add
dict_example['d'] = 4  # new key, add 

print("updated dictionary: ", dict_example)

The output is:

Output
original dictionary: {'a': 1, 'b': 2} updated dictionary: {'a': 100, 'b': 2, 'c': 3, 'd': 4}

The output shows that the value of a is overwritten by the new value, the value of b is unchanged, and new key-value pairs are added for c and d.

Add to Python Dictionary Without Overwriting Values

Using the = assignment operator overwrites the values of existing keys with the new values. If you know that your program might have duplicate keys, but you don’t want to overwrite the original values, then you can conditionally add values using an if statement.

Continuing with the example from the preceding section, you can use if statements to add only new key-value pairs to the dictionary:

dict_example = {'a': 1, 'b': 2}

print("original dictionary: ", dict_example)

dict_example['a'] = 100  # existing key, overwrite
dict_example['c'] = 3  # new key, add
dict_example['d'] = 4  # new key, add 

print("updated dictionary: ", dict_example)

# add the following if statements

if 'c' not in dict_example.keys():
    dict_example['c'] = 300

if 'e' not in dict_example.keys():
    dict_example['e'] = 5

print("conditionally updated dictionary: ", dict_example)

The output is:

Output
original dictionary: {'a': 1, 'b': 2} updated dictionary: {'a': 100, 'b': 2, 'c': 3, 'd': 4} conditionally updated dictionary: {'a': 100, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

The output shows that, because of the if condition, the value of c didn’t change when the dictionary was conditionally updated.

Add to Python Dictionary Using the update() Method

You can append a dictionary or an iterable of key-value pairs to a dictionary using the update() method. The update() method overwrites the values of existing keys with the new values.

The following example demonstrates how to create a new dictionary, use the update() method to add a new key-value pair and a new dictionary, and print each result:

site = {'Website':'DigitalOcean', 'Tutorial':'How To Add to a Python Dictionary'}
print("original dictionary: ", site)

# update the dictionary with the author key-value pair
site.update({'Author':'Sammy Shark'})
print("updated with Author: ", site)

# create a new dictionary
guests = {'Guest1':'Dino Sammy', 'Guest2':'Xray Sammy'}

# update the original dictionary with the new dictionary
site.update(guests)
print("updated with new dictionary: ", site)

The output is:

Output
original dictionary: {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary'} updated with Author: {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'Sammy Shark'} updated with new dictionary: {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'Sammy Shark', 'Guest1': 'Dino Sammy', 'Guest2': 'Xray Sammy'}

The output shows that the first update adds a new key-value pair and the second update adds the key-value pairs from the guest dictionary to the site dictionary. Note that if your update to a dictionary includes an existing key, then the old value is overwritten by the update.

Add to Python Dictionary Using the Merge | Operator

You can use the dictionary merge | operator, represented by the pipe character, to merge two dictionaries and return a new dictionary object.

The following example demonstrates how to to create two dictionaries and use the merge operator to create a new dictionary that contains the key-value pairs from both:

site = {'Website':'DigitalOcean', 'Tutorial':'How To Add to a Python Dictionary', 'Author':'Sammy'}

guests = {'Guest1':'Dino Sammy', 'Guest2':'Xray Sammy'}

new_site = site | guests

print("site: ", site)
print("guests: ", guests)
print("new_site: ", new_site)

The output is:

Output
site: {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'Sammy'} guests: {'Guest1': 'Dino Sammy', 'Guest2': 'Xray Sammy'} new_site: {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'Sammy', 'Guest1': 'Dino Sammy', 'Guest2': 'Xray Sammy'}

The two dictionaries were merged into a new dictionary object that contains the key-value pairs from both dictionaries.

If a key exists in both dictionaries, then the value from the second dictionary, or right operand, is the value taken. In the following example code, both dictionaries have a key called b:

dict1 = {'a':'one', 'b':'two'}
dict2 = {'b':'letter two', 'c':'letter three'}

dict3 = dict1 | dict2

print{"dict3: ", dict3}

The output is:

Output
dict3: {'a': 'one', 'b': 'letter two', 'c': 'letter three'}

The value of key b was overwritten by the value from the right operand, dict2.

Add to Python Dictionary Using the Update |= Operator

You can use the dictionary update |= operator, represented by the pipe and equal sign characters, to update a dictionary in-place with the given dictionary or values.

Just like the merge | operator, if a key exists in both dictionaries, then the update |= operator takes the value from the right operand.

The following example demonstrates how to create two dictionaries, use the update operator to append the second dictionary to the first dictionary, and then print the updated dictionary:

site = {'Website':'DigitalOcean', 'Tutorial':'How To Add to a Python Dictionary', 'Author':'Sammy'}

guests = {'Guest1':'Dino Sammy', 'Guest2':'Xray Sammy'}

site |= guests

print("site: ", site)

The output is:

Output
site: {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'Sammy', 'Guest1': 'Dino Sammy', 'Guest2': 'Xray Sammy'}

In the preceding example, you didn’t need to create a third dictionary object, because the update operator modifies the original object. The output shows that the guests dictionary was appended to the original site dictionary.

Conclusion

In this article, you used different methods to add to and update a Python dictionary. Continue your learning with more Python tutorials.

Additionally, you can explore the collections module, which provides alternatives like defaultdict and Counter for more advanced dictionary operations. For more information, refer to the tutorials on Python Counter and Using the Collections Module in Python.

FAQs

How do I add things to a dictionary in Python?

To add an item to a dictionary, you use the syntax:

dictionary[key] = value

This will add a new key-value pair to the dictionary. If the key already exists, its value will be updated.

For example:

my_dict = {"a": 1}
my_dict["b"] = 2
print(my_dict)  # Output: {'a': 1, 'b': 2}

Can you append to a dictionary?

You cannot directly use methods like .append() for dictionaries as they are used for lists. However, you can add a key-value pair using dictionary[key] = value. To append values to an existing list stored in a dictionary, you need to modify the list.

my_dict = {"a": [1, 2]}
my_dict["a"].append(3)
print(my_dict)  # Output: {'a': [1, 2, 3]}

How do you add multiple items to a dictionary in Python?

You can use the .update() method to add multiple key-value pairs from another dictionary or an iterable of key-value pairs.

my_dict = {"a": 1}
my_dict.update({"b": 2, "c": 3})
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}

Or using an iterable

my_dict.update([("d", 4), ("e", 5)])
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

How to add to an empty dictionary in Python?

You can start with an empty dictionary {} and add items using dictionary[key] = value.

my_dict = {}
my_dict["a"] = 1
print(my_dict)  # Output: {'a': 1}

How to modify a dictionary in Python?

You can modify a dictionary by updating its existing key-value pairs or adding new ones.

my_dict = {"a": 1, "b": 2}
my_dict["a"] = 10  # Modify existing key
my_dict["c"] = 3   # Add a new key
print(my_dict)  # Output: {'a': 10, 'b': 2, 'c': 3}

How to add values to keys in a dictionary?

If the values are numeric, you can add directly. If the values are lists, you can append to them.

Example with numbers:

my_dict = {"a": 1}
my_dict["a"] += 2
print(my_dict)  # Output: {'a': 3}

Example with lists:

my_dict = {"a": [1]}
my_dict["a"].append(2)
print(my_dict)  # Output: {'a': [1, 2]}

How do you add items to a dictionary in Python without overwriting?

Before adding, you can check if the key exists using the below:

my_dict = {"a": 1}
if "b" not in my_dict:
    my_dict["b"] = 2
print(my_dict)  # Output: {'a': 1, 'b': 2}

What is dict() in Python?

dict() is a built-in function that creates a new dictionary. You can create an empty dictionary or initialize it with key-value pairs.

my_dict = dict()  # Empty dictionary
my_dict = dict(a=1, b=2)  # With key-value pairs
print(my_dict)  # Output: {'a': 1, 'b': 2}

How do you sum values in a Python dictionary?

You can use the sum() function if the values are numeric.

my_dict = {"a": 10, "b": 20, "c": 30}
total = sum(my_dict.values())
print(total)  # Output: 60

To learn more about dictionaries in Python, refer to this tutorial on Understanding Dictionaries in Python.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author


Default avatar

Sr Technical Writer

Sr. Technical Writer@ DigitalOcean | Medium Top Writers(AI & ChatGPT) | 2M+ monthly views & 34K Subscribers | Ex Cloud Consultant @ AMEX | Ex SRE(DevOps) @ NUTANIX


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
April 25, 2021

how can add new column in tuple # List of tuples listofTuples = [(“Riti” , 11), (“Aadi” , 12), (“Sam” , 13),(“John” , 22),(“Lucy” , 90)] thank

- hamza

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    February 7, 2021

    Thank you, this information was clearly laid out!

    - KMJ248

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      October 14, 2020

      You don`t need keys() d={c: alpha} if c in d: pass

      - RTFM

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        June 24, 2020

        What will happen if you don’t add the .keys()? will it also check if the values of keys are the value you want to input?

        - Niik

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          May 7, 2020

          thanks it really helped! have a question tho, can you make mathematical operations in the values to the keys?

          - confused

            Try DigitalOcean for free

            Click below to sign up and get $200 of credit to try our products over 60 days!

            Sign up

            Join the Tech Talk
            Success! Thank you! Please check your email for further details.

            Please complete your information!

            Become a contributor for community

            Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

            DigitalOcean Documentation

            Full documentation for every DigitalOcean product.

            Resources for startups and SMBs

            The Wave has everything you need to know about building a business, from raising funding to marketing your product.

            Get our newsletter

            Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

            New accounts only. By submitting your email you agree to our Privacy Policy

            The developer cloud

            Scale up as you grow — whether you're running one virtual machine or ten thousand.

            Get started for free

            Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

            *This promotional offer applies to new accounts only.