Should we use update or value assignment?

In #2 of this exercise we are told to do the following:

Without changing the definition of the dictionary oscar_winners, change the value associated with the key “Best Picture” to “Moonlight”.

I used the following code:

Both of these appear to generate the same output. But for the purposes of this exercise, which is more correct? Does one ‘change the definition’ of oscar_winners and one not?

What is the difference and in what cases should I use one method over the other?

Thanks for reading!

No ‘should’ about it. Either method is fine. The advantage of using update can be seen when we have multiple key/value pairs to insert or update. The subscript method is one key/value at a time. update takes a dictionary or an iterable such as a list of tuples.

:rofl:

It’s always a little tricky to do timings on such a small set of operations (and small objects). One of the biggest differences you have here is that with your update method you create two entirely different dictionary objects and then combine them, the subscript syntax just modifies a single dictionary (each piece of {key:value} syntax creates a new dictionary).

So I’d be inclined to use .update when I have already have the relevant objects, be that two dictionaries or a dictionary and something storing key-value pairs which is the same guidance as provided above.

Data Science Parichay

  • Python Add or Update Item in Dictionary

Dictionaries are quite useful and commonly used in python. It may happen that you require to add new keys or update an existing one in a dictionary. In this tutorial, we’ll look at how you can add or update items in a dictionary.

Before we proceed, here’s a quick refresher on dictionaries in python – Dictionaries are a collection of items used for storing key to value mappings. They are mutable and hence we can update the dictionary by adding new key-value pairs, removing existing key-value pairs, or changing the value corresponding to a key. For more, check out our guide on  dictionaries and other data structures in python.

How to add or update items in a dictionary ?

You can use the subscript notation, which is, accessing the key or creating a new one using square brackets [] and then providing the corresponding value. Also, you can use the dictionary method update() to add or update a key in an existing dictionary. There are other ways as well but for the purpose of this tutorial we’ll be limiting to these two are they are the common ones.

Using the subscript notation

The subscript notation is used to refer the value corresponding a key in a dictionary. For example, in the dictionary d = {'a':1, 'b':2} , the subscript notation d['a'] will give you the value corresponding to the key 'a' in the dictionary.

To add a new key to the dictionary you can simply use the subscript notation with the new key and assign its respective value using the assignment operator = .

Example : Add a new key to the dictionary using subscript notation

In the above example, the dictionary shares stores the number of shares of different companies in a sample portfolio. The key represents the company and the value represents the number of shares of the company in the portfolio. A new key TSLA is added to the dictionary with the value 80 using the subscript notation.

Introductory ⭐

  • Harvard University Data Science: Learn R Basics for Data Science
  • Standford University Data Science: Introduction to Machine Learning
  • UC Davis Data Science: Learn SQL Basics for Data Science
  • IBM Data Science: Professional Certificate in Data Science
  • IBM Data Analysis: Professional Certificate in Data Analytics
  • Google Data Analysis: Professional Certificate in Data Analytics
  • IBM Data Science: Professional Certificate in Python Data Science
  • IBM Data Engineering Fundamentals: Python Basics for Data Science

Intermediate ⭐⭐⭐

  • Harvard University Learning Python for Data Science: Introduction to Data Science with Python
  • Harvard University Computer Science Courses: Using Python for Research
  • IBM Python Data Science: Visualizing Data with Python
  • DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization

Advanced ⭐⭐⭐⭐⭐

  • UC San Diego Data Science: Python for Data Science
  • UC San Diego Data Science: Probability and Statistics in Data Science using Python
  • Google Data Analysis: Professional Certificate in Advanced Data Analytics
  • MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
  • MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science

🔎  Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

To update an existing key you can simply refer to it using the subscript notation and they change its value.

Example: Update an existing key using the subscript notation

In the above example, the existing value corresponding to the key 'GOOG' is changed to 150 using the subscript notation.

The subscript notation, that is accessing and changing keys using the square brackets [] is a simple and intuitive way of adding or updating a dictionary.

Using the update() function

update() is a dictionary function in python used to update a dictionary by changing the values of existing keys or adding new keys.

Example : Add a new key to the dictionary using the update function

In the above example, the new key TSLA with the value 80 is added to the dictionary using the dictionary function update() . Note that the update() function modifies the dict in-place .

Example: Update an existing key using the update function

In the above example, the update() function is used to update the value of the existing key 'GOOG' to 150 .

For more on the update function refer to the python docs.

Tutorials on python dictionaries –

  • Python Dictionary Clear – With Examples
  • Python Dictionary Pop vs Popitem
  • Python view dictionary Keys and Values
  • Python Dictionary Items – With Examples
  • Python Dictionary Get – With Examples

Subscribe to our newsletter for more informative guides and tutorials. We do not spam and you can opt out any time.

Piyush Raj

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

View all posts

Add and update an item in a dictionary in Python

This article explains how to add an item (key-value pair) to a dictionary ( dict ) or update the value of an existing item in Python.

Add or update a single item in a dictionary

Specify keyword arguments, specify an iterable of key-value pairs, specify other dictionaries.

See the following articles to learn how to add a dictionary to a dictionary (i.e., merge dictionaries), remove an item from a dictionary, and change a key name.

  • Merge dictionaries in Python
  • Remove an item from a dictionary in Python (clear, pop, popitem, del)
  • Change a key name in a dictionary in Python

You can add an item to a dictionary or update the value of an existing item as follows.

If a non-existent key is specified, a new item is added; if an existing key is specified, the value of that item is updated (overwritten).

To avoid updating the value for an existing key, use the setdefault() method. See the following article for details.

  • Add an item if the key does not exist in dict with setdefault in Python

Add or update multiple items in a dictionary: update()

You can add or update multiple items at once using the update() method.

  • Built-in Types - dict.update() — Python 3.11.3 documentation

If the keyword argument ( key=value ) is specified for update() , the item with that key and value is added. If the key already exists, it is overwritten with the value specified in the argument.

An error is raised if the same key is specified multiple times.

In this case, keys must be valid identifiers in Python. They cannot start with a number or contain symbols other than _ .

  • Valid variable names and naming rules in Python

In other approaches, values that are invalid as identifiers can be used as keys.

You can pass a list of (key, value) pairs to update() . If a key in the list duplicates an existing key, it is overwritten with the value specified in the argument.

In the above example, a list of tuples was specified. However, any iterable containing key-value pairs (two-element iterables) is acceptable. This could include a tuple of lists, such as ([key1, value1], [key2, value2], ...) , or other iterable structures.

You can use zip() to add items by pairing elements from a list of keys and a list of values.

  • zip() in Python: Get elements from multiple lists

When using an iterable of key-value pairs, duplicate keys are acceptable. The value corresponding to the later occurrence of a key will overwrite the earlier one.

You can specify another dictionary as an argument to update() to add all its items.

Passing multiple dictionaries directly to update() will result in an error. You can prefix dictionaries with ** and pass each element as a keyword argument.

  • Expand and pass a list and dictionary as arguments in Python

When using ** , as shown in the above example, duplicate keys between the caller's dictionary and the dictionary specified in the argument are not a problem. However, if the same keys are found across multiple dictionaries specified in the argument, this will result in an error.

For more details on merging dictionaries, refer to the following article.

Related Categories

Related articles.

  • Check if a key/value exists in a dictionary in Python
  • Set operations on multiple dictionary keys in Python
  • Get keys from a dictionary by value in Python
  • Create a dictionary in Python ({}, dict(), dict comprehensions)
  • Get a value from a dictionary by key in Python
  • Extract specific key values from a list of dictionaries in Python
  • Swap keys and values in a dictionary in Python
  • Get maximum/minimum values and keys in Python dictionaries
  • Iterate through dictionary keys and values in Python
  • Pretty-print with pprint in Python
  • Sort a list of dictionaries by the value of the specific key in Python

Adventures in Machine Learning

Mastering python dictionary updates: techniques and examples.

Updating a Python Dictionary: Everything You Need to Know

A Python dictionary is a powerful data structure that enables the storage of key-value pairs where the key is unique and the value can be of different types such as int, float, string, and others. However, there are times when we may need to update the content of a dictionary in order to add, modify or remove values.

In this article, we will explore different methods to update a Python dictionary and provide examples to help you understand how it works. Using the dict.update() method

One way to update a Python dictionary is to use the built-in method update().

This method allows adding or modifying key-value pairs from an existing dictionary, or even copying the entire content of another dictionary to an empty dictionary. Syntax: dict.update([other])

– dict: the dictionary to be updated

– other: a dictionary or an iterable object containing key-value pairs to be added to the dictionary

For example, if we have a dictionary with names and phone numbers and wish to add a new key-value pair, we can use the update() method:

# Create a dictionary with names and phone numbers

contacts = {‘Lucy’: 123456, ‘John’: 987654}

# Add a new phone number for Tim

contacts.update({‘Tim’: 555555})

print(contacts)

# Output: {‘Lucy’: 123456, ‘John’: 987654, ‘Tim’: 555555}

We can also use the update() method to modify an existing key-value pair. For instance, to change Tim’s phone number, we can run:

contacts.update({‘Tim’: 678910})

# Output: {‘Lucy’: 123456, ‘John’: 987654, ‘Tim’: 678910}

Updating with an Iterable

In addition to dictionaries, the update() method can also accept iterables such as lists, tuples, and sets. To update a dictionary with an iterable, we simply need to pass a list of tuples where each tuple represents a key-value pair.

Syntax: dict.update(iterable)

– iterable: an iterable object containing key-value pairs to be added to the dictionary

Here is an example where we add new key-value pairs to a dictionary from a list of tuples:

# Create a dictionary

scores = {‘Alice’: 90, ‘Bob’: 80}

# Update the dictionary with new scores

new_scores = [(‘Charlie’, 70), (‘David’, 85)]

scores.update(new_scores)

print(scores)

# Output: {‘Alice’: 90, ‘Bob’: 80, ‘Charlie’: 70, ‘David’: 85}

Alternatively, we can use the append() method to add new items to a list, then update the dictionary with the modified list.

fruits = {‘apple’: 2, ‘banana’: 3}

# Update the dictionary with a list of new items

new_fruits = [‘orange’, ‘pear’]

fruits[‘grape’] = 4

fruits[‘cherry’] = 5

fruits.update(zip(new_fruits, [4,2]))

print(fruits)

# Output: {‘apple’: 2, ‘banana’: 3, ‘grape’: 4, ‘cherry’: 5, ‘orange’: 4, ‘pear’: 2}

Updating Nested Python Dictionary

A nested dictionary in Python is a dictionary inside another dictionary. In this case, when we want to update an Inner value, we have to reference both the Outer key and the Inner key.

myDict = {‘cars’: {‘bmw’: 20, ‘audi’: 15, ‘honda’: 5},

‘bikes’: {‘harley’: 10, ‘indian’: 7, ‘bmw’: 3}}

To update the value of the Inner Key bmw in the Outer dictionary Key cars:

# Access the value of the Key cars and key bmw

myDict[‘cars’][‘bmw’]

# Update the value of the Key bmw in Cars

myDict[‘cars’][‘bmw’] = 25

print(myDict)

# Output: {‘cars’: {‘bmw’: 25, ‘audi’: 15, ‘honda’: 5}, ‘bikes’: {‘harley’: 10, ‘indian’: 7, ‘bmw’: 3}}

Examples and Syntax

Updating a value in a dictionary.

Using the key of an existing item, we can update the value in a Python dictionary with the following syntax:

Syntax: dict[key] = new_value

– key: the key that corresponds to the existing item

– new_value: the new value to be assigned to the item

pets = {‘dog’: 3, ‘cat’: 2, ‘fish’: 1}

# Update the value of the item with key ‘fish’

pets[‘fish’] = 2

print(pets)

# Output: {‘dog’: 3, ‘cat’: 2, ‘fish’: 2}

Updating a Dictionary with an Iterable

An iterable such as a list, tuple or set can also be used to update a dictionary. In this case, we can loop through the iterable and extract the key-value pairs to add to the dictionary.

Syntax: dict[key] = value for key, value in iterable

– iterable: an iterable containing key-value pairs to be added to the dictionary

– key: the key of each key-value pair in the iterable

– value: the value of each key-value pair in the iterable

names = {‘Alice’: 1, ‘Bob’: 2, ‘Charlie’: 3}

# Update the dictionary with values from a tuple

new_values = [(‘David’, 4), (‘Eva’, 5), (‘Frank’, 6)]

for key, value in new_values:

names[key] = value

print(names)

# Output: {‘Alice’: 1, ‘Bob’: 2, ‘Charlie’: 3, ‘David’: 4, ‘Eva’: 5, ‘Frank’: 6}

Updating Nested Dictionary with respective key values

We may also need to update a specific key-value pair in a nested dictionary. In this case, we can reference the keys of both the outer and inner dictionaries to update the value.

Syntax: dict[outer_key][inner_key] = new_value

– outer_key: the key that corresponds to the outer dictionary

– inner_key: the key that corresponds to the inner dictionary

– new_value: the new value to be assigned to the inner item

# Create a nested dictionary

inventory = {‘fruit’: {‘apple’: 10, ‘banana’: 20},

‘vegetable’: {‘carrot’: 5, ‘broccoli’: 3}}

# Update the value of the item with key ‘banana’ in ‘fruit’

inventory[‘fruit’][‘banana’] = 25

print(inventory)

# Output: {‘fruit’: {‘apple’: 10, ‘banana’: 25}, ‘vegetable’: {‘carrot’: 5, ‘broccoli’: 3}}

Python dictionaries are a powerful data structure that allows easy storage and retrieval of key-value pairs. Updating the content of a dictionary can be achieved using different methods, such as the update() method, iteration, and direct assignment of new values to keys.

By following the examples and syntax provided in this article, you can easily update your dictionaries and keep your data up-to-date. A Python dictionary is a flexible data structure that allows the storage of key-value pairs where the key is unique and the value can be of different data types.

In this article, we covered different methods to update values in a Python dictionary and demonstrated how to use them with examples. Updating a Python dictionary can be achieved using the `update()` method which allows adding, modifying or deleting key-value pairs.

We also looked at how to update the dictionary with an iterable such as a list using the `zip()` function, iterate over a list using a `for loop`, or directly assign new values to keys in the dictionary. One advantage of a Python dictionary is the ability to create nested dictionaries, where a dictionary is contained within another dictionary.

Updating a nested dictionary requires reference to both the outer key and the inner key. Using the methods outlined in this article and with practice, Python developers can efficiently manage their dictionaries’ contents and manipulate data in a meaningful way.

In this addition, we will delve deeper into the Python dictionary and explore different use-cases and applications of updating key-value pairs. Updating Values in a Python Dictionary: Use Cases

Python dictionaries are widely used in data modeling where it provides a fast and efficient way of representing complex data.

Updating values in a dictionary is a crucial part of data modeling because it allows for the creation of dynamic and responsive datasets. For instance, in a student management system, a dictionary can be used to store student records in the form of key-value pairs, with the key representing a unique ID and the value corresponding to the student’s details such as name, age, and exam scores.

The update() method can be used to update a student’s exam scores, allowing their grades to be updated as they submit new coursework or take a new exam. In a banking system, a dictionary can be used to store customer accounts, with the key representing the account number and the value corresponding to the customer’s details such as name, address, and account balance.

The update() method can be used to update the account balance when the customer deposits or withdraws funds. In a web application, a dictionary can be used to store user preferences, with the key representing the user ID and the value corresponding to their preferred settings such as theme, font size, and language.

The update() method can be used to update the user preferences when the user changes their settings. Updating a dictionary in this manner provides a robust solution for dynamic applications because the data can be manipulated and updated in real-time, allowing the application to respond to the user’s input immediately.

Nested Dictionaries in Python

A nested dictionary is a dictionary inside another dictionary. It allows for the creation of more complex data structures and provides an efficient way of storing and updating data.

For instance, in a hotel reservation system, a dictionary can be used to store room reservations, with the key representing the room number and the value corresponding to the guest’s details such as name, check-in, and check-out dates. A nested dictionary can be used to store additional details such as the room type, bed size, and price.

The outer dictionary stores the room number as the key. Inside the outer dictionary comes the inner dictionary.

The inner dictionary holds the room details such as type, size, and price. This nested structure allows efficient updating of the reservation data while still keeping the room details organized.

To update a nested dictionary, we use the same method as updating the outer dictionary, but with an additional level of reference to the inner dictionary. This involves referencing the key of the outer dictionary and the key of the inner dictionary to update the value.

Here is an example of a nested dictionary:

101: {‘type’: ‘single’, ‘size’: ‘king’, ‘price’: 70},

102: {‘type’: ‘single’, ‘size’: ‘queen’, ‘price’: 60},

201: {‘type’: ‘double’, ‘size’: ‘king’, ‘price’: 110},

202: {‘type’: ‘double’, ‘size’: ‘queen’, ‘price’: 100}}

We can update the price of a room using the following code:

rooms[101][‘price’] = 80

This updates the price of room 101 to $80, making it easier to keep track of and manage hotel room rates.

Conclusion:

Updating a Python dictionary is a crucial part of data modeling as it allows for dynamic and responsive datasets. The built-in method update() allows adding, modifying, or deleting key-value pairs.

Additionally, updating dictionaries with iterables provides an efficient way of adding new values. Nested dictionaries offer an excellent solution for creating more complex data structures, providing a robust solution for dynamic applications.

By using the methods and examples provided in this article, Python developers can create powerful applications with efficient and responsive data modeling. In summary, updating a Python dictionary is a crucial aspect of data modeling, allowing for dynamic and responsive datasets.

The built-in update() method, along with iteration and direct assignment, provide various methods to efficiently update key-value pairs. The use of nested dictionaries provides a robust solution for creating more complex data structures.

Updating a nested dictionary requires reference to both the outer and inner key. By employing the methods and examples provided in this article, Python developers can create powerful applications with efficient and responsive data modeling.

Therefore, Python developers should master updating a Python dictionary to develop dynamic applications that respond to the user’s input immediately.

Popular Posts

Mastering pandas dataframe row selection in python, the ultimate guide to reactjs development: features functions and basic web app building, mastering time and time zone data in postgresql: a practical guide.

  • Terms & Conditions
  • Privacy Policy

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python dictionary methods.

  • Python Dictionary clear()

Python Dictionary copy()

Python Dictionary fromkeys()

  • Python Dictionary get()

Python Dictionary items()

Python Dictionary keys()

  • Python Dictionary popitem()
  • Python Dictionary setdefault()
  • Python Dictionary pop()
  • Python Dictionary values()

Python Dictionary update()

Python tutorials.

  • Python Set update()
  • Python Dictionary

The update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.

Syntax of Dictionary update()

The syntax of update() is:

update() Parameters

The update() method takes either a dictionary or an iterable object of key/value pairs (generally tuples ).

If update() is called without passing parameters, the dictionary remains unchanged.

Return Value from update()

update() method updates the dictionary with elements from a dictionary object or an iterable object of key/value pairs.

It doesn't return any value (returns None ).

Example 1: Working of update()

Note : The update() method adds element(s) to the dictionary if the key is not in the dictionary. If the key is in the dictionary, it updates the key with the new value.

Example 2: update() When Tuple is Passed

Here, we have passed a list of tuples [('y', 3), ('z', 0)] to the update() function. In this case, the first element of tuple is used as the key and the second element is used as the value.

Sorry about that.

Python References

Python Library

Python Dictionary update() Method + Examples

In this Python tutorial , we will understand the use of the Python Dictionary update() method.

The Python Dictionary update() method is used to update the value of an existing key-value pair. However, if the key with the same name does not exist, it will add the key value automatically to the dictionary.

Here we will understand the following topics related to the Python Dictionary update().

  • Introduction to Python Dictionary update()
  • Syntax of Python Dictionary update()
  • Examples of Python Dictionary update()

Table of Contents

In this section, we will discuss what is Python Dictionary update() .

Python Dictionary is an unordered collection of data values, that is used to store data values like a tuple, which does not like other Data Types that contain only a single value, instead it stores data in key-value pairs.

The dictionary.update() is a Python Dictionary method utilized to update the dictionary with the key and value pairs.

However, it inserts a key-value pair in the dictionary if it is not present. Also, it updates the key-value pair if it already exists in the dictionary.

Next, let us look at the syntax of using the dictionary.update() in Python

  • other: This parameter can either be a dictionary or an iterable of key-value pairs.

Return value

This function does not return any values, rather it updates the same input dictionary with the newly associated values of the keys.

However, if try to fetch the value returned by dictionary.update() , we will get None as a result.

Read: Python Dictionary sort

Now that we understood the syntax of using the dictionary.update() , let us discuss a few examples of using this method in Python.

Example 1: Updating existing key-value in Dictionary

In this example, we updated the value of the Country key from the United States to the United Kingdom using the dictionary.update() method.

Once we run the above Python program, we will get the following result.

Also, check: Python Dictionary index

Example 2: Updating a dictionary using another dictionary

In the above example, we defined 2 dictionaries- user and user_details . After this, we used the update() method on the user dictionary to add the data of user_details to the user .

In the end, we will get the user dictionary as follows in Python.

Read: Python dictionary multiple values

Example 3: Updating a dictionary using key-value pairs

In this example, instead of adding key-value pairs as a dictionary, we specify key-value pairs directly in the update() method.

Once we execute the above Python program, we will get the following result.

Example 4: Updating a dictionary using a list of tuples

In this example, we defined a list of tuples where each tuple represents a key-value pair. After this, we utilized the list of tuples in the update() method to add these key-value pairs to the user dictionary.

The final result of the above python program is given below.

Python Dictionary update()

So, in this section, we understood how to use the dictionary.update() method in Python to update the key-value pairs of an existing Python Dictionary.

You may like the following Python tutorials:

  • Python Dictionary of sets
  • Python dictionary initialize
  • Python dictionary contains

So, in this Python tutorial, we understood what Python Dictionary update() method is. Here we covered the syntax of using the dictionary.update() and various examples of how to update dictionary values using it.

Here is the set of topics that we covered.

Bijay - Python Expert

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile .

  • Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs
  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python

Related Articles

  • Solve Coding Problems
  • Python Dictionary Methods
  • Python Dictionary clear()
  • Python Dictionary copy()
  • Python Dictionary fromkeys() Method
  • Python Dictionary get() Method
  • Python Dictionary items() method
  • Python Dictionary keys() method
  • Python Dictionary pop() Method
  • Python Dictionary popitem() method
  • Python Dictionary setdefault() Method

Python Dictionary update() method

  • Python dictionary values()

Python Dictionary update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.

Syntax of Python Dictionary Update Method

The dictionary update() method in Python has the following syntax:

Syntax: dict.update([other]) Parameters: This method takes either a dictionary or an iterable object of key/value pairs (generally tuples) as parameters. Returns: It doesn’t return any value but updates the Dictionary with elements from a dictionary object or an iterable object of key/value pairs.

Python Dictionary update() Example

Let us see a few examples of the update() method to update the data of the Python dictionary .

Update with another Dictionary

Here we are updating a dictionary in Python using the update() method and passing another dictionary to it as parameters. The second dictionary is used for the updated value.

Update with an Iterable

In this example, instead of using another dictionary, we passed an iterable value to the update() function.

Python Dictionary Update Value if the Key Exists

In this example, we will update the value of a dictionary in Python if the particular key exists. If the key is not present in the dictionary, we will simply print that the key does not exist.

Python Dictionary Update Value if the Key doesn’t Exist

Here, we will try to update the value of the dictionary whose key does not exist in the dictionary. In this case, the key and value will be added as the new element in the dictionary.

Please Login to comment...

  • python-dict
  • Python-dict-functions
  • kumar_satyam
  • harendrakumar123
  • ajaymaheshwari3692
  • tanya_sehgal
  • 10 Best ChatGPT Prompts for Lawyers 2024
  • What is Meta’s new V-JEPA model? [Explained]
  • What is Chaiverse & How it Works?
  • Top 10 Mailchimp Alternatives (Free) - 2024
  • Dev Scripter 2024 - Biggest Technical Writing Event By GeeksforGeeks

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Assign a dictionary Key or Value to variable in Python

avatar

Last updated: Feb 21, 2023 Reading time · 4 min

banner

# Table of Contents

  • Assign a dictionary value to a Variable in Python
  • Assign dictionary key-value pairs to variables in Python
  • Assign dictionary key-value pairs to variables using exec()

# Assign a dictionary value to a Variable in Python

Use bracket notation to assign a dictionary value to a variable, e.g. first = my_dict['first_name'] .

The left-hand side of the assignment is the variable's name and the right-hand side is the value.

assign dictionary value to variable

The first example uses square brackets to access a dictionary key and assigns the corresponding value to a variable.

If you need to access the dictionary value using an index , use the dict.values() method.

The dict.values method returns a new view of the dictionary's values.

We had to use the list() class to convert the view object to a list because view objects are not subscriptable (cannot be accessed at an index).

You can use the same approach if you have the key stored in a variable.

If you try to access a dictionary key that doesn't exist using square brackets, you'd get a KeyError .

On the other hand, the dict.get() method returns None for non-existent keys by default.

The dict.get method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.

The method takes the following 2 parameters:

If a value for the default parameter is not provided, it defaults to None , so the get() method never raises a KeyError .

If you need to assign the key-value pairs of a dictionary to variables, update the locals() dictionary.

# Assign dictionary key-value pairs to variables in Python

Update the locals() dictionary to assign the key-value pairs of a dictionary to variables.

assign dictionary key value pairs to variables

The first example uses the locals() dictionary to assign the key-value pairs of a dictionary to local variables.

The locals() function returns a dictionary that contains the current scope's local variables.

The dict.update method updates the dictionary with the key-value pairs from the provided value.

You can access the variables directly after calling the dict.update() method.

The SimpleNamespace class can be initialized with keyword arguments.

The keys of the dictionary are accessible as attributes on the namespace object.

Alternatively, you can use the exec() function.

# Assign dictionary key-value pairs to variables using exec()

This is a three-step process:

  • Iterate over the dictionary's items.
  • Use the exec() function to assign each key-value pair to a variable.
  • The exec() function supports dynamic execution of Python code.

assign dictionary key value pairs to variables using exec

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

On each iteration, we use the exec() function to assign the current key-value pair to a variable.

The exec function supports dynamic execution of Python code.

The function takes a string, parses it as a suite of Python statements and runs the code.

Which approach you pick is a matter of personal preference. I'd go with the SimpleNamespace class to avoid any linting errors for trying to access undefined variables.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • Check if all values in a Dictionary are equal in Python
  • How to Replace values in a Dictionary in Python
  • Get multiple values from a Dictionary in Python
  • Get random Key and Value from a Dictionary in Python
  • Join the Keys or Values of Dictionary into String in Python
  • Multiply the Values in a Dictionary in Python
  • Print specific key-value pairs of a dictionary in Python
  • How to set all Dictionary values to 0 in Python
  • Sum all values in a Dictionary or List of Dicts in Python
  • Swap the keys and values in a Dictionary in Python

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

We Love Servers.

  • WHY IOFLOOD?
  • BARE METAL CLOUD
  • DEDICATED SERVERS

Python Update Dictionary: Methods and Usage Guide

Python dictionary being updated code snippets arrows and Python logo

Are you finding it challenging to update dictionaries in Python? You’re not alone. Many developers find themselves puzzled when it comes to handling this task, but we’re here to help.

Think of Python’s dictionaries as a well-organized bookshelf – allowing us to store and manage data in an efficient and accessible manner. Python dictionaries, like a well-organized bookshelf, can be easily updated and managed.

In this guide, we’ll walk you through the process of updating dictionaries in Python , from the basics to more advanced techniques. We’ll cover everything from the simple update() method to more complex techniques like dictionary comprehension and merging dictionaries, as well as alternative approaches.

Let’s dive in and start mastering Python dictionaries!

TL;DR: How Do I Update a Dictionary in Python?

To update a dictionary in Python, you can use the update() method, like dict1.update({'b': 3, 'c': 4}) . This method allows you to add new items or change the value of existing items in a Python dictionary.

Here’s a simple example:

In this example, we have a dictionary dict1 with keys ‘a’ and ‘b’. We use the update() method to change the value of ‘b’ and add a new key-value pair ‘c’: 4. The updated dictionary now includes ‘a’: 1, ‘b’: 3, and ‘c’: 4.

This is a basic way to update a dictionary in Python, but there’s much more to learn about handling dictionaries. Continue reading for a more detailed explanation and additional methods.

Table of Contents

Understanding Python’s update() Method

Advanced techniques for updating dictionaries in python, exploring alternative methods for updating dictionaries in python, troubleshooting common issues in python dictionary updates, understanding python’s dictionary data type, exploring the impact of dictionary updates in python, wrapping up: mastering python dictionary updates.

Python’s update() function is a simple yet powerful tool for updating dictionaries. This method allows you to add new items or modify existing ones, making it a go-to solution for many developers.

Let’s take a look at a basic example:

In this example, dict1 is our original dictionary with keys ‘a’ and ‘b’. We then use the update() method to change the value of ‘b’ from 2 to 3 and add a new key-value pair ‘c’: 4 to the dictionary.

Advantages of the update() Method

The update() method is straightforward and easy to use, making it a great way to update dictionaries in Python for beginners. It’s also very flexible, as it can accept dictionaries, iterables with key-value pairs, and keyword arguments.

Potential Pitfalls of the update() Method

While the update() method is powerful, it’s important to use it correctly. One common pitfall is trying to update a dictionary with a key that doesn’t exist. In this case, the update() method will add a new key-value pair to the dictionary, which might not be the desired outcome.

Another potential issue is trying to update a dictionary with a non-iterable object. The update() method requires an iterable, so trying to use a non-iterable will result in a TypeError.

As you become more comfortable with Python and its dictionaries, you may want to explore more advanced techniques for updating dictionaries. These methods include using dictionary comprehension, merging dictionaries, and using the ** operator.

Dictionary Comprehension

Dictionary comprehension is a concise and readable way to create and update dictionaries. Here’s how you can use it to update a dictionary:

In this example, we have two dictionaries: original_dict and update_dict . We use dictionary comprehension to merge these two dictionaries into new_dict . The values from update_dict overwrite the values from original_dict for any common keys.

Merging Dictionaries

Python also provides the | operator to merge two dictionaries. It’s similar to using the update() method or dictionary comprehension:

Again, the values from update_dict overwrite the values from original_dict for any common keys.

The ** Operator

The ** operator is another way to merge dictionaries in Python. It works similarly to the | operator and dictionary comprehension:

This code creates a new dictionary new_dict by merging original_dict and update_dict . The ** operator unpacks the dictionaries and overwrites the values of original_dict with the values of update_dict for any common keys.

These advanced techniques provide more flexibility and control when updating dictionaries in Python. However, they also require a deeper understanding of Python’s syntax and concepts. Always remember to choose the method that best fits your needs and the specific task at hand.

As we delve deeper into Python’s capabilities, we discover that there are alternative ways to update dictionaries. These methods include using the setdefault() method and leveraging third-party libraries.

Using the setdefault() Method

The setdefault() method in Python is a less common, but still useful, way to update dictionaries. This method returns the value of a key if it exists. However, if the key does not exist, it inserts the key with a specified value.

Here’s an example:

In this case, the key ‘c’ did not exist in the dictionary dict1 , so the setdefault() method added ‘c’: 3 to the dictionary.

Leveraging Third-Party Libraries

Third-party libraries can also provide alternative ways to update dictionaries. For example, the collections library’s defaultdict function can be used to automatically assign a default value to non-existent keys when they’re accessed, effectively updating the dictionary.

In this example, we create a defaultdict where non-existent keys return a default value of 0. When we access ‘c’, which doesn’t exist in dict1 , it returns 0.

These alternative methods offer more flexibility and functionality, but they may also add complexity to your code. It’s essential to understand the trade-offs and choose the method that best suits your specific needs.

As with any programming task, updating dictionaries in Python can sometimes lead to unexpected issues. In this section, we’ll discuss some common problems you might encounter and provide solutions and tips to help you navigate these challenges.

Dealing with Key Errors

One common issue when updating dictionaries is encountering a KeyError . This error occurs when you try to access or update a key that doesn’t exist in the dictionary.

In this example, we’re trying to print the value of ‘c’, which doesn’t exist in dict1 , resulting in a KeyError .

To avoid this, you can use the get() method, which returns None if the key doesn’t exist, or a default value that you can specify.

Handling Type Errors

Another common issue is a TypeError , which occurs when you try to use an unhashable type, like a list, as a dictionary key.

In this example, we’re trying to use a list ['a'] as a key, which is not allowed in Python dictionaries. To solve this, you can convert the list to a tuple, which is hashable and can be used as a dictionary key.

These are just a few examples of the issues you might encounter when updating dictionaries in Python. Understanding these common problems and their solutions can help you write more robust and error-free code.

Before we delve deeper into updating dictionaries, it’s essential to understand what a dictionary in Python is and why it’s a powerful data structure.

A dictionary in Python is an unordered collection of data values used to store data values like a map. It’s a mutable data type that stores data in key:value pairs. Unlike other data types that hold only a single value as an element, dictionaries hold key:value pairs.

In this example, my_dict is a dictionary with three key-value pairs. The keys are ‘name’, ‘age’, and ‘profession’, and the corresponding values are ‘John’, 27, and ‘Engineer’.

One of the main features of dictionaries that makes them unique is the fact that they are mutable, i.e., we can change, add or remove items after the dictionary is created. This is where the update() method and other techniques for updating dictionaries come into play.

Understanding the fundamental nature of Python’s dictionary data type is crucial for grasping the concepts underlying dictionary updates. With this knowledge, you’ll be better equipped to handle dictionary updates and tackle any related challenges.

Python’s dictionary updates are not just a stand-alone operation. In fact, they play a significant role in various areas of programming and data manipulation. Let’s explore how they impact different domains.

Dictionary Updates in Data Manipulation

In data manipulation, Python dictionaries are often used to store and manipulate data. Updating dictionaries allows us to modify this data dynamically, which is crucial in data analysis.

Python Dictionary Updates in Web Scraping

Web scraping often involves handling large amounts of data. Python dictionaries serve as an efficient way to store and manage this data. Updating dictionaries allows us to add, modify, or delete data as we scrape websites.

Exploring Related Concepts

While updating dictionaries is a fundamental task, there are several related concepts that are worth exploring. These include nested dictionaries, where a dictionary contains other dictionaries as values, and other dictionary methods like pop() , clear() , and copy() .

In this example, we have a nested dictionary nested_dict . We update the age of the person in dict1 from 27 to 28 using dictionary update techniques.

Further Resources for Python Dictionary Mastery

To dive deeper into Python dictionaries and their manipulation, you might find the following resources helpful:

  • Python Dictionary Examples and Syntax – Learn the ins and outs of Python dictionaries, from basic usage to advanced techniques, with this complete IOFlood guide.

Adding Entries to Python Dictionaries : A How-To Guide by IOFlood – Discover methods to add new entries to Python dictionaries.

Python Nested Dictionary Tutorial: Creating and Accessing – Master the art of creating and manipulating nested dictionaries.

Python Documentation: Dictionaries – A comprehensive guide to dictionaries straight from Python’s official documentation.

Real Python’s Dictionaries in Python – An in-depth tutorial on Python dictionaries, including how to update, iterate over, and manipulate them.

Dictionary Manipulation in Python by PythonForBeginners – A beginner-friendly guide to dictionary manipulation in Python, including updating dictionaries.

In this comprehensive guide, we’ve delved into the process of updating dictionaries in Python. We’ve explored how a simple data structure like a dictionary can be efficiently manipulated using Python’s built-in methods and some advanced techniques.

We began with the basics, introducing the concept of Python dictionaries and how to update them using the update() method. We then moved onto more advanced techniques, covering dictionary comprehension, merging dictionaries, and the use of the ** operator. We also explored alternative methods such as the setdefault() method and leveraging third-party libraries.

Along the way, we tackled common issues you might encounter when updating dictionaries, such as KeyError and TypeError . We provided solutions and workarounds for these challenges, equipping you to handle any roadblocks in your Python dictionary journey.

Here’s a quick comparison to the options we discussed:

Whether you’re just starting out with Python dictionaries or looking to enhance your data manipulation skills, we hope this guide has provided you with a deeper understanding of how to update dictionaries in Python.

Understanding how to update dictionaries in Python is a crucial skill for any Python programmer. With this knowledge, you’re now equipped to handle and manipulate dictionary data more effectively. Happy coding!

About Author

Gabriel Ramuglia

Gabriel Ramuglia

Gabriel is the owner and founder of IOFLOOD.com , an unmanaged dedicated server hosting company operating since 2010.Gabriel loves all things servers, bandwidth, and computer programming and enjoys sharing his experience on these topics with readers of the IOFLOOD blog.

Related Posts

Bash script for substring extraction featuring text cropping icons and selection markers emphasizing precision and text analysis

TutorialsTonight Logo

Python Dictionary Update

In this tutorial, you will learn how to update a dictionary in Python. You will learn how to add new key-value pairs to a dictionary and how to update existing items in a dictionary.

Dictionary is a mutable data type in Python. It means that we can change the contents of a dictionary after it has been created. We can add or update key-value pairs in a dictionary.

Table of Contents

  • Update if Key Exists
  • Alternative to update()

Python dictionary update

update() Method in Dictionary

The update() method in Python dictionary is used to add or update key-value pairs in a dictionary.

Parameters:

  • other (optional) - dictionary or iterable of key/value pairs (default is None)

Example 1: Add new key-value pairs to a dictionary

If the key is not present in the dictionary, then the update() method adds the key-value pair to the dictionary.

Key in the dictionary below so, the item will be added

Example 2: Update existing items in a dictionary

If the key is already present in the dictionary, then the update() method updates the value of the key with the new value.

Key in the dictionary below so, the item will be updated

Example 3: Add new key-value pairs to a dictionary using iterable

We can also add new key-value pairs to a dictionary using an iterable of key-value pairs (list of tuples).

Example 4: Update and add existing items in a dictionary using iterable

We can also update existing items in a dictionary using an iterable of key-value pairs (list of tuples).

Example 5: Update and add items in a dictionary using keyword arguments

We can also update existing items in a dictionary using keyword arguments.

Python Dictionary Update if Key Exists

To update a value in a dictionary only if the key exists, we can use an if-else statement in python to check if the key exists in the dictionary.

If the key exists, then we update the value of the key. Otherwise, we do nothing.

Alternative to Python Dictionary Update

You can also update an item of a dictionary using the [ ] and = operators.

To update an item, we first access the item using the key and then assign a new value to it.

Let's see an example to understand this.

Frequently Asked Questions

Can Python dictionary be modified?

Yes, the Python dictionary is mutable. We can add, update, and delete items from a dictionary.

How do you update a dictionary in Python?

Use the update() method and pass the dictionary or iterable of key-value pairs as an argument (You can also use assignment operator). If the key is already present in the dictionary, then the update() method updates the value of the key with the new value. If the key is not present in the dictionary, then the update() method adds the key-value pair to the dictionary.

Does dictionary update overwrite?

Yes, if the key is already present in the dictionary, then the update() method updates the value of the key with the new value.

Dictionary Merge and Update Operators in Python 3.9

python dict update vs assignment

Introduction

Python 3.9 was released on Oct. 5, 2020 and it introduces some neat features and optimizations including PEP 584, Union Operators in the built-in class dict ; the so-called Dictionary Merge and Update Operators.

In this blog post we will go over the new operators to see if there are any advantages or disadvantages of using them over the earlier ways of merging and updating dictionaries.

The Dictionary Merge Operator

Given two or more dictionaries, we fuse them into a single one.

Let's start by diving into a short example demonstrating the old way of merging two dictionaries:

This merge creates an entirely new dict object z where we unpack every value from x and y . This way of merging two dictionaries feels unnatural and hardly obvious. If both dictionaries have the same keys, the values of dictionary x are overwritten by the values of dictionary y .

According to Guido:

"I'm sorry for PEP 448, but even if you know about d in simpler contexts, if you were to ask a typical Python user how to combine two dicts into a new one, I doubt many people would think of {**d1, **d2} . I know I myself had forgotten about it when this thread started! If you were to ask a newbie who has learned a few things (e.g. sequence concatenation) they would much more likely guess d1+d2."

Here's an example demonstrating the new dictionary merge operator, | :

But remember that the merge operator creates new dictionaries and leaves the two merged dictionaries unchanged:

If the expression isn't assigned to a variable, it will be lost.

The same concept applies to the legacy merging method:

So we have seen they have similar behaviors, and using the merge operator | allows us to write cleaner code but besides this, what good is it for?

The operators have also been implemented for several other standard library packages like collections .

To demonstrate the usefulness of the merge operator, | , let's take a look at the following example using defaultdict :

By using the double asterisk, ** , merging the two dictionaries will work, but the method is not aware of the class object so we will end up with a traditional dictionary instead:

The power of the merge operator | is that it is aware of the class objects. As such, a defaultdict will be returned:

Note: the order of operands is very important as they will behave differently depending on the order they are arranged. In the example above we use both placements so the latter keys and values overwrite the former ones.

Another advantage using the new dictionary merge operator | is having chained expressions following this syntax: dict4 = dict1 | dict2 | dict3 , equivalent to dict4 = {**dict1, **dict2, **dict3} .

Let us show a practical example:

The Dictionary Update Operator

In the following example, the dictionary x is being updated by the dictionary y , demonstrating the .update() method:

The dictionary x was updated, and due to the nature of how the built-in .update() method is designed, it operates in-place . The dictionary gets updated but the method returns None .

Using the update operator , |= , we can achieve the same functionality with a cleaner syntax:

However, compared to the legacy .update() method, the new dictionary update operator helps prevent misuse by throwing a SyntaxError if we use it inside a print statement, and the dictionary does not get updated. In the next line, following the required syntax the dictionary was updated successfully.

Let's see how updating the dictionary either with the legacy .update() method or with the update operator |= , does not change the object's id nor it creates a new one:

Another example is extending dictionaries with a list of tuples by using the update operator |= :

The example above is syntactic sugar for the legacy .update() method:

Besides the better syntax that the new dictionary update operator |= has to offer, another advantage of using it is a safer dictionary update by throwing a SyntaxError instead of None when using it inside print .

Older versions The dictionary update operator |= and the merge operator | are new features in Python 3.9, so if you are trying to use them in an earlier version you will encounter an error similar to this, so make sure you update to the latest version:

The new operators are not here to replace the existing ways of merging and updating, but rather to complement them. Some of the major takeaways are:

  • the merge operator , | , is class aware, offers a better syntax and it creates a new object.
  • the update operator , |= , operates in-place , catches common errors before they happen and it doesn't create a new object.
  • the operators are new features in Python 3.9

If you're learning Python and you find this kind of content interesting, be sure to follow us on Twitter or sign up to our mailing list to stay up to date with all out content. There's a form at the bottom of the page if you're interested.

We also just did a big update to our Complete Python Course , so check that out if you're interested in getting to an advanced level in Python. We have a 30 day money back guarantee, so you really have nothing to lose by giving it a try. We'd love to have you!

Python Dictionary update() Method

Python Dictionary update() Method

The dict.update() method updates a dictionary with a (key-value) pair element from another dictionary , or from an iterable of (key-value) pair elements.

  • The dict.update() method inputs either an iterable object of (key-value) pair elements ( tuples in most cases), or another dictionary.
  • Also, if the Python dict.update() method is applied to a dictionary without any parameters passed, then no changes to the dictionary occur, so the dictionary remains the same.

💡 Side note : The dict.update() method inserts a specified (key-value) pair element into a dictionary if the key does not exist.

Return Value

  • The Python dict.update() method performs it’s update operation, but does not return any value (returns a None value).

Basic Example

Example using the Python dict.update() method to update the value of a key in a dictionary:

This example shows how to update a value of a particular key in a dictionary by passing another dictionary with the key and its changed value as a parameter to the dict.update() method.

Add Key Value Pair to Python Dictionary

The following example shows how to add (key-value) pair elements to a Python dictionary using the dict.update() method:

This example shows how to individually insert (key-value) pair elements into a dictionary.

Passing a Tuple to dict.update()

An example on how to pass a tuple to a Python dictionary using the dict.update() method:

In the previous example, applying the dict.update() method to a dictionary with one (key-value) pair element is good when only one (key-value) pair element needs to be inserted into a dictionary,

But this operation becomes tedious if multiple (key-value) pair elements are required to be inserted into a dictionary. This example of passing a tuple to the Python dict.update() method is very useful because multiple (key-value) pair elements can be inserted into a dictionary, all at once.

Merge Two Nested Dictionaries with dict.update()

Example on how to merge two nested dictionaries using the Python dictionary method dict.update() :

Attempted merging of nested dictionaries failed, resulting in a None value being returned. But you can see that the original dictionary in company_1 has changed:

Python Enhancement Proposals

  • Python »
  • PEP Index »

PEP 584 – Add Union Operators To dict

Dict.update, {**d1, **d2}, collections.chainmap, dict(d1, **d2), specification, reference implementation, add the values (as counter does, with + ), leftmost value (first-seen) wins, concatenate values in a list, use the addition operator, use the left shift operator, use a new left arrow operator, disadvantages, ipython/zmq/ipkernel.py, ipython/zmq/kernelapp.py, matplotlib/backends/backend_svg.py, matplotlib/delaunay/triangulate.py, matplotlib/legend.py, numpy/ma/core.py, praw/internal.py, pygments/lexer.py, requests/sessions.py, sphinx/domains/__init__.py, sphinx/ext/doctest.py, sphinx/ext/inheritance_diagram.py, sphinx/highlighting.py, sphinx/quickstart.py, sympy/abc.py, sympy/parsing/maxima.py, sympy/printing/ccode.py and sympy/printing/fcode.py, sympy/utilities/runtests.py, related discussions.

This PEP proposes adding merge ( | ) and update ( |= ) operators to the built-in dict class.

After this PEP was accepted, the decision was made to also implement the new operators for several other standard library mappings .

The current ways to merge two dicts have several disadvantages:

d1.update(d2) modifies d1 in-place. e = d1.copy(); e.update(d2) is not an expression and needs a temporary variable.

Dict unpacking looks ugly and is not easily discoverable. Few people would be able to guess what it means the first time they see it, or think of it as the “obvious way” to merge two dicts.

As Guido said :

I’m sorry for PEP 448, but even if you know about **d in simpler contexts, if you were to ask a typical Python user how to combine two dicts into a new one, I doubt many people would think of {**d1, **d2} . I know I myself had forgotten about it when this thread started!

{**d1, **d2} ignores the types of the mappings and always returns a dict . type(d1)({**d1, **d2}) fails for dict subclasses such as defaultdict that have an incompatible __init__ method.

ChainMap is unfortunately poorly-known and doesn’t qualify as “obvious”. It also resolves duplicate keys in the opposite order to that expected (“first seen wins” instead of “last seen wins”). Like dict unpacking, it is tricky to get it to honor the desired subclass. For the same reason, type(d1)(ChainMap(d2, d1)) fails for some subclasses of dict.

Further, ChainMaps wrap their underlying dicts, so writes to the ChainMap will modify the original dict:

This “neat trick” is not well-known, and only works when d2 is entirely string-keyed:

The new operators will have the same relationship to the dict.update method as the list concatenate ( + ) and extend ( += ) operators have to list.extend . Note that this is somewhat different from the relationship that | / |= have with set.update ; the authors have determined that allowing the in-place operator to accept a wider range of types (as list does) is a more useful design, and that restricting the types of the binary operator’s operands (again, as list does) will help avoid silent errors caused by complicated implicit type casting on both sides.

Key conflicts will be resolved by keeping the rightmost value. This matches the existing behavior of similar dict operations, where the last seen value always wins:

All of the above follow the same rule. This PEP takes the position that this behavior is simple, obvious, usually the behavior we want, and should be the default behavior for dicts. This means that dict union is not commutative; in general d | e != e | d .

Similarly, the iteration order of the key-value pairs in the dictionary will follow the same semantics as the examples above, with each newly added key (and its value) being appended to the current sequence.

Dict union will return a new dict consisting of the left operand merged with the right operand, each of which must be a dict (or an instance of a dict subclass). If a key appears in both operands, the last-seen value (i.e. that from the right-hand operand) wins:

The augmented assignment version operates in-place:

Augmented assignment behaves identically to the update method called with a single positional argument, so it also accepts anything implementing the Mapping protocol (more specifically, anything with the keys and __getitem__ methods) or iterables of key-value pairs. This is analogous to list += and list.extend , which accept any iterable, not just lists. Continued from above:

When new keys are added, their order matches their order within the right-hand mapping, if any exists for its type.

One of the authors has written a C implementation .

An approximate pure-Python implementation is:

Major Objections

Dict union is not commutative.

Union is commutative, but dict union will not be ( d | e != e | d ).

There is precedent for non-commutative unions in Python:

While the results may be equal, they are distinctly different. In general, a | b is not the same operation as b | a .

Dict Union Will Be Inefficient

Giving a pipe operator to mappings is an invitation to writing code that doesn’t scale well. Repeated dict union is inefficient: d | e | f | g | h creates and destroys three temporary mappings.

The same argument applies to sequence concatenation.

Sequence concatenation grows with the total number of items in the sequences, leading to O(N**2) (quadratic) performance. Dict union is likely to involve duplicate keys, so the temporary mappings will not grow as fast.

Just as it is rare for people to concatenate large numbers of lists or tuples, the authors of this PEP believe that it will be rare for people to merge large numbers of dicts. collections.Counter is a dict subclass that supports many operators, and there are no known examples of people having performance issues due to combining large numbers of Counters. Further, a survey of the standard library by the authors found no examples of merging more than two dicts, so this is unlikely to be a performance problem in practice… “Everything is fast for small enough N”.

If one expects to be merging a large number of dicts where performance is an issue, it may be better to use an explicit loop and in-place merging:

Dict Union Is Lossy

Dict union can lose data (values may disappear); no other form of union is lossy.

It isn’t clear why the first part of this argument is a problem. dict.update() may throw away values, but not keys; that is expected behavior, and will remain expected behavior regardless of whether it is spelled as update() or | .

Other types of union are also lossy, in the sense of not being reversible; you cannot get back the two operands given only the union. a | b == 365 … what are a and b ?

Only One Way To Do It

Dict union will violate the Only One Way koan from the Zen.

There is no such koan. “Only One Way” is a calumny about Python originating long ago from the Perl community.

More Than One Way To Do It

Okay, the Zen doesn’t say that there should be Only One Way To Do It. But it does have a prohibition against allowing “more than one way to do it”.

There is no such prohibition. The “Zen of Python” merely expresses a preference for “only one obvious way”:

The emphasis here is that there should be an obvious way to do “it”. In the case of dict update operations, there are at least two different operations that we might wish to do:

  • Update a dict in place : The Obvious Way is to use the update() method. If this proposal is accepted, the |= augmented assignment operator will also work, but that is a side-effect of how augmented assignments are defined. Which you choose is a matter of taste.
  • Merge two existing dicts into a third, new dict : This PEP proposes that the Obvious Way is to use the | merge operator.

In practice, this preference for “only one way” is frequently violated in Python. For example, every for loop could be re-written as a while loop; every if block could be written as an if / else block. List, set and dict comprehensions could all be replaced by generator expressions. Lists offer no fewer than five ways to implement concatenation:

  • Concatenation operator: a + b
  • In-place concatenation operator: a += b
  • Slice assignment: a[len(a):] = b
  • Sequence unpacking: [*a, *b]
  • Extend method: a.extend(b)

We should not be too strict about rejecting useful functionality because it violates “only one way”.

Dict Union Makes Code Harder To Understand

Dict union makes it harder to tell what code means. To paraphrase the objection rather than quote anyone in specific: “If I see spam | eggs , I can’t tell what it does unless I know what spam and eggs are”.

This is very true. But it is equally true today, where the use of the | operator could mean any of:

  • int / bool bitwise-or
  • set / frozenset union
  • any other overloaded operation

Adding dict union to the set of possibilities doesn’t seem to make it harder to understand the code. No more work is required to determine that spam and eggs are mappings than it would take to determine that they are sets, or integers. And good naming conventions will help:

What About The Full set API?

dicts are “set like”, and should support the full collection of set operators: | , & , ^ , and - .

This PEP does not take a position on whether dicts should support the full collection of set operators, and would prefer to leave that for a later PEP (one of the authors is interested in drafting such a PEP). For the benefit of any later PEP, a brief summary follows.

Set symmetric difference ( ^ ) is obvious and natural. For example, given two dicts:

the symmetric difference d1 ^ d2 would be {"spam": 1, "ham": 3} .

Set difference ( - ) is also obvious and natural, and an earlier version of this PEP included it in the proposal. Given the dicts above, we would have d1 - d2 be {"spam": 1} and d2 - d1 be {"ham": 3} .

Set intersection ( & ) is a bit more problematic. While it is easy to determine the intersection of keys in two dicts, it is not clear what to do with the values . Given the two dicts above, it is obvious that the only key of d1 & d2 must be "eggs" . “Last seen wins”, however, has the advantage of consistency with other dict operations (and the proposed union operators).

What About Mapping And MutableMapping ?

collections.abc.Mapping and collections.abc.MutableMapping should define | and |= , so subclasses could just inherit the new operators instead of having to define them.

There are two primary reasons why adding the new operators to these classes would be problematic:

  • Currently, neither defines a copy method, which would be necessary for | to create a new instance.
  • Adding |= to MutableMapping (or a copy method to Mapping ) would create compatibility issues for virtual subclasses.

Rejected Ideas

Rejected semantics.

There were at least four other proposed solutions for handling conflicting keys. These alternatives are left to subclasses of dict.

It isn’t clear that this behavior has many use-cases or will be often useful, but it will likely be annoying as any use of the dict union operator would have to be guarded with a try / except clause.

Too specialised to be used as the default behavior.

It isn’t clear that this behavior has many use-cases. In fact, one can simply reverse the order of the arguments:

This is likely to be too specialised to be the default. It is not clear what to do if the values are already lists:

Should this give {'a': [1, 2, 3, 4]} or {'a': [[1, 2], [3, 4]]} ?

Rejected Alternatives

This PEP originally started life as a proposal for dict addition, using the + and += operator. That choice proved to be exceedingly controversial, with many people having serious objections to the choice of operator. For details, see previous versions of the PEP and the mailing list discussions .

The << operator didn’t seem to get much support on Python-Ideas, but no major objections either. Perhaps the strongest objection was Chris Angelico’s comment

The “cuteness” value of abusing the operator to indicate information flow got old shortly after C++ did it.

Another suggestion was to create a new operator <- . Unfortunately this would be ambiguous, d <- e could mean d merge e or d less-than minus e .

Use A Method

A dict.merged() method would avoid the need for an operator at all. One subtlety is that it would likely need slightly different implementations when called as an unbound method versus as a bound method.

As an unbound method, the behavior could be similar to:

As a bound method, the behavior could be similar to:

  • Arguably, methods are more discoverable than operators.
  • The method could accept any number of positional and keyword arguments, avoiding the inefficiency of creating temporary dicts.
  • Accepts sequences of (key, value) pairs like the update method.
  • Being a method, it is easy to override in a subclass if you need alternative behaviors such as “first wins”, “unique keys”, etc.
  • Would likely require a new kind of method decorator which combined the behavior of regular instance methods and classmethod . It would need to be public (but not necessarily a builtin) for those needing to override the method. There is a proof of concept .
  • It isn’t an operator. Guido discusses why operators are useful . For another viewpoint, see Alyssa Coghlan’s blog post .

Use a Function

Instead of a method, use a new built-in function merged() . One possible implementation could be something like this:

An alternative might be to forgo the arbitrary keywords, and take a single keyword parameter that specifies the behavior on collisions:

  • Most of the same advantages of the method solutions above.
  • Doesn’t require a subclass to implement alternative behavior on collisions, just a function.
  • May not be important enough to be a builtin.
  • Hard to override behavior if you need something like “first wins”, without losing the ability to process arbitrary keyword arguments.

The authors of this PEP did a survey of third party libraries for dictionary merging which might be candidates for dict union.

This is a cursory list based on a subset of whatever arbitrary third-party packages happened to be installed on one of the authors’ computers, and may not reflect the current state of any package. Also note that, while further (unrelated) refactoring may be possible, the rewritten version only adds usage of the new operators for an apples-to-apples comparison. It also reduces the result to an expression when it is efficient to do so.

Rewrite as:

The above examples show that sometimes the | operator leads to a clear increase in readability, reducing the number of lines of code and improving clarity. However other examples using the | operator lead to long, complex single expressions, possibly well over the PEP 8 maximum line length of 80 columns. As with any other language feature, the programmer should use their own judgement about whether | improves their code.

Mailing list threads (this is by no means an exhaustive list):

  • Dict joining using + and +=
  • PEP: Dict addition and subtraction
  • PEP 584: Add + and += operators to the built-in dict class.
  • Moving PEP 584 forward (dict + and += operators)
  • PEP 584: Add Union Operators To dict
  • Accepting PEP 584: Add Union Operators To dict

Ticket on the bug tracker

Merging two dictionaries in an expression is a frequently requested feature. For example:

https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression

https://stackoverflow.com/questions/1781571/how-to-concatenate-two-dictionaries-to-create-a-new-one-in-python

https://stackoverflow.com/questions/6005066/adding-dictionaries-together-python

Occasionally people request alternative behavior for the merge:

https://stackoverflow.com/questions/1031199/adding-dictionaries-in-python

https://stackoverflow.com/questions/877295/python-dict-add-by-valuedict-2

…including one proposal to treat dicts as sets of keys .

Ian Lee’s proto-PEP , and discussion in 2015. Further discussion took place on Python-Ideas .

(Observant readers will notice that one of the authors of this PEP was more skeptical of the idea in 2015.)

Adding a full complement of operators to dicts .

Discussion on Y-Combinator .

https://treyhunner.com/2016/02/how-to-merge-dictionaries-in-python/

https://code.tutsplus.com/tutorials/how-to-merge-two-python-dictionaries–cms-26230

In direct response to an earlier draft of this PEP, Serhiy Storchaka raised a ticket in the bug tracker to replace the copy(); update() idiom with dict unpacking.

This document is placed in the public domain or under the CC0-1.0-Universal license, whichever is more permissive.

Source: https://github.com/python/peps/blob/main/peps/pep-0584.rst

Last modified: 2023-10-11 12:05:51 GMT

COMMENTS

  1. python dict.update vs. subscript to add a single key/value pair

    python dict.update vs. subscript to add a single key/value pair [closed] Ask Question Asked 10 years, 11 months ago Modified 1 month ago Viewed 26k times 66 It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form.

  2. Should we use update or value assignment?

    #option one is to use the update method: oscar_winners.update ( {"Best Picture": "Moonlight"}) #option two is this value assignment: oscar_winners ["Best Picture"] = "Moonlight" Both of these appear to generate the same output. But for the purposes of this exercise, which is more correct?

  3. Python Add or Update Item in Dictionary

    Python Add or Update Item in Dictionary / Article / By Piyush Raj Dictionaries are quite useful and commonly used in python. It may happen that you require to add new keys or update an existing one in a dictionary. In this tutorial, we'll look at how you can add or update items in a dictionary.

  4. Add and update an item in a dictionary in Python

    You can add an item to a dictionary or update the value of an existing item as follows. dict_object[key] = value If a non-existent key is specified, a new item is added; if an existing key is specified, the value of that item is updated (overwritten).

  5. Mastering Python Dictionary Updates: Techniques and Examples

    One way to update a Python dictionary is to use the built-in method update(). ... and direct assignment of new values to keys. By following the examples and syntax provided in this article, you can easily update your dictionaries and keep your data up-to-date. A Python dictionary is a flexible data structure that allows the storage of key-value ...

  6. Python Dictionary update()

    The update () method takes either a dictionary or an iterable object of key/value pairs (generally tuples ). If update () is called without passing parameters, the dictionary remains unchanged.

  7. Python Dictionary Update() Method + Examples

    The dictionary.update () is a Python Dictionary method utilized to update the dictionary with the key and value pairs. However, it inserts a key-value pair in the dictionary if it is not present. Also, it updates the key-value pair if it already exists in the dictionary. Next, let us look at the syntax of using the dictionary.update () in Python

  8. Python Dictionary update() method

    The dictionary update () method in Python has the following syntax: Syntax: dict.update ( [other]) Parameters: This method takes either a dictionary or an iterable object of key/value pairs (generally tuples) as parameters.

  9. Assign a dictionary Key or Value to variable in Python

    The left-hand side of the assignment is the variable's name and the right-hand side is the value. main.py. ... # Assign dictionary key-value pairs to variables in Python. Update the locals() dictionary to assign the key-value pairs of a dictionary to variables. main.py. ... You can access the variables directly after calling the dict.update ...

  10. Python Update Dictionary: Methods and Usage Guide

    To update a dictionary in Python, you can use the update() method, like dict1.update({'b': 3, 'c': 4}). This method allows you to add new items or change the value of existing items in a Python dictionary. Here's a simple example:

  11. Python's Assignment Operator: Write Robust Assignments

    Adding and Updating Dictionary Keys Doing Parallel Assignments Unpacking Iterables Providing Default Argument Values Augmented Assignment Operators in Python Augmented Mathematical Assignment Operators Augmented Assignments for Concatenation and Repetition Augmented Bitwise Assignment Operators Other Assignment Variants

  12. Dictionaries in Python

    Dictionaries differ from lists primarily in how elements are accessed: List elements are accessed by their position in the list, via indexing. Dictionary elements are accessed via keys.

  13. Python Dictionary Update (with Examples)

    If the key is already present in the dictionary, then the update () method updates the value of the key with the new value. Example Key in the dictionary below so, the item will be updated dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3} print("Before update:", dict1) # update value of key 'b' in dict1 dict1.update(dict2) print("After update:", dict1)

  14. Dictionary Merge and Update Operators in Python 3.9

    Python 3.9 was released on Oct. 5, 2020 and it introduces some neat features and optimizations including PEP 584, Union Operators in the built-in class dict; the so-called Dictionary Merge and Update Operators. In this blog post we will go over the new operators to see if there are any advantages or disadvantages of using them over the earlier ...

  15. Python Dictionary update () Method

    Parameters. The dict.update () method inputs either an iterable object of (key-value) pair elements ( tuples in most cases), or another dictionary. Also, if the Python dict.update () method is applied to a dictionary without any parameters passed, then no changes to the dictionary occur, so the dictionary remains the same.

  16. Use of add (), append (), update () and extend () in Python

    append has a popular definition of "add to the very end", and extend can be read similarly (in the nuance where it means "...beyond a certain point"); sets have no "end", nor any way to specify some "point" within them or "at their boundaries" (because there are no "boundaries"!), so it would be highly misleading to suggest that these operations...

  17. PEP 584

    Rationale. The new operators will have the same relationship to the dict.update method as the list concatenate (+) and extend (+=) operators have to list.extend.Note that this is somewhat different from the relationship that | / |= have with set.update; the authors have determined that allowing the in-place operator to accept a wider range of types (as list does) is a more useful design, and ...

  18. Fastest way to update a dictionary in python

    1 How can you even have this problem? Normally you'd know which keys you've set before or simply build the final dict in one go. - Jochen Ritzel Nov 11, 2010 at 16:06 1 I am calculating all the elements (and relations) in an Algebra. And I have to use what I know to find out the ones I don't know.

  19. python dict update vs assign

    © 2024 Google LLC Download this code from https://codegive.com Dictionaries in Python are versatile data structures that allow you to store and manipulate key-value pairs. Two...