Python update all values in dict

How to update a Python dictionary values?

Values of a Python Dictionary can be updated using the following two ways i.e. using the update() method and also, using square brackets.

Dictionary represents the key-value pair in Python, enclosed in curly braces. The keys are unique and a colon separates it from value, whereas comma separates the items. With that, the left size before the colon are keys, whereas right its corresponding values.

Let us first create a Python Dictionary and fetch all the values. Here, we have included 4 key-value pairs in the Dictionary and displayed them. Product, Model, Units, and Available are keys of the Dictionary. Except the Units key, all are having String values −

Example

# Creating a Dictionary with 4 key-value pairs myprod = "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" > # Displaying the Dictionary print(myprod) # Displaying individual values print("Product token punctuation">,myprod["Product"]) print("Model token punctuation">,myprod["Model"]) print("Units token punctuation">,myprod["Units"]) print("Available token punctuation">,myprod["Available"])

Output

 Product = Mobile Model = XUT Units = 120 Available = Yes

Above, we have displayed the 4-key-value pairs in a Dictionary with Product Information. Now, we will see the two ways to update Dictionary values in Python.

Dictionary Update Using The Update Method

Let us now update the Dictionary values using the update() method. We have first displayed the Dictionary before updating the values. After that, the update() is used and the updated values are placed as a parameter of the method. Here, we have updated only two key values i.e. Product and Model

Example

# Creating a Dictionary with 4 key-value pairs myprod = "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" > # Displaying the Dictionary print("Dictionary = \n",myprod) print("Product token punctuation">,myprod["Product"]) print("Model token punctuation">,myprod["Model"]) # Updating Dictionary Values myprod.update("Product":"SmartTV","Model": "PHRG6",>) # Displaying the Updated Dictionary print("\nUpdated Dictionary = \n",myprod) print("Updated Product token punctuation">,myprod["Product"]) print("Updated Model token punctuation">,myprod["Model"])

Output

Dictionary = Product = Mobile Model = XUT Updated Dictionary = Updated Product = SmartTV Updated Model = PHRG6

In the output, we can see the 1st two values updated using the updated() method, rest remained the same.

Dictionary Update Using The Square Brackets

Here is another code. Let us now update the Dictionary values without using the update() method. We will use the square brackets to update individual values. Here, we have updated only two key values i.e. Units and Available. The square brackets have the corresponding keys for the values to be updated −

Example

# Creating a Dictionary with 4 key-value pairs myprod = "Product":"Mobile", "Model": "XUT", "Units": 120, "Available": "Yes" > # Displaying the Dictionary print("Dictionary = \n",myprod) print("Product token punctuation">,myprod["Product"]) print("Model token punctuation">,myprod["Model"]) # Updating Dictionary Values myprod["Units"] = 170 myprod["Available"] = "No" # Displaying the Updated Dictionary print("\nUpdated Dictionary = \n",myprod) print("Updated Units token punctuation">,myprod["Units"]) print("Updated Availability token punctuation">,myprod["Available"])

Output

Dictionary = Product = Mobile Model = XUT Updated Dictionary = Updated Units = 170 Updated Availability = No

In the output, we can see the last two values updated without using the updated() method, rest remained the same.

Источник

Python update all values in dict

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

banner

# Table of Contents

# Replace values in a dictionary in Python

Use the dict.update() method to replace values in a dictionary.

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

Copied!
my_dict = 'name': 'default', 'site': 'default', 'id': 1, 'topic': 'Python' > my_dict.update( 'name': 'borislav', 'site': 'bobbyhadz.com' > ) # 👇️ print(my_dict)

We used the dict.update method to replace values in a dictionary.

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

The method overrides the dictionary’s existing keys and returns None.

The dict.update() method can either be called with another dictionary or an iterable of key-value pairs (e.g. a list of tuples with 2 elements each).

# Passing keyword arguments to the dict.update() method

You can also pass keyword arguments to the dict.update() method.

Copied!
my_dict = 'name': 'default', 'site': 'default', 'id': 1, 'topic': 'Python' > my_dict.update( [ ('name', 'borislav'), ('site', 'bobbyhadz.com') ] ) # 👇️ print(my_dict)

Alternatively, you can use the dictionary unpacking ** operator.

# Replace values in a dictionary using dictionary unpacking

This is a three-step process:

  1. Use the dictionary unpacking operator to unpack the key-value pairs into a new dictionary.
  2. Specify the keys with the updated values.
  3. The new values will override the values of the existing keys.
Copied!
my_dict = 'name': 'default', 'site': 'default', 'id': 1, 'topic': 'Python' > my_dict = **my_dict, 'name': 'borislav', 'site': 'bobbyhadz.com' > # 👇️ print(my_dict)

We used the dictionary unpacking ** operator to unpack the key-value pairs of the dictionary into a new dictionary.

The name and site keys override the values of the existing keys with the same names.

Alternatively, you can use a for loop.

# Replace values in a dictionary using a for loop

This is a three-step process:

  1. Use a for loop to iterate over the dictionary’s items.
  2. Check if each value should be updated.
  3. Replace the matching values.
Copied!
my_dict = 'name': 'default', 'site': 'default', 'id': 1, 'topic': 'Python' > for key, value in my_dict.items(): if value == 'default': if key == 'name': my_dict[key] = 'borislav' elif key == 'site': my_dict[key] = 'bobbyhadz.com' # 👇️ print(my_dict)

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

Copied!
my_dict = 'name': 'default', 'site': 'default', 'id': 1, 'topic': 'Python' > # 👇️ dict_items([('name', 'default'), ('site', 'default'), ('id', 1), ('topic', 'Python')]) print(my_dict.items())

On each iteration, we check if the current value should be replaced and replace the matching values.

# Replace values in a dictionary using the dictionary merge operator

You can also use the dictionary merge operator to replace values in a dictionary.

Copied!
my_dict = 'name': 'default', 'site': 'default', 'id': 1, 'topic': 'Python' > my_dict = my_dict | 'name': 'bobby hadz', 'site': 'bobbyhadz.com' > # # 'id': 1, 'topic': 'Python'> print(my_dict)

The dictionary merge (|) operator is available starting with Python version 3.9.

You can check your version of Python by running the following command.

The dictionary merge (|) operator creates a new dictionary.

The is also a dictionary update (|=) operator that is used for assignment.

Copied!
my_dict = 'name': 'default', 'site': 'default', 'id': 1, 'topic': 'Python' > my_dict |= 'name': 'bobby hadz', 'site': 'bobbyhadz.com' > # # 'id': 1, 'topic': 'Python'> print(my_dict)

Make sure your version of Python is 3.9 or more recent to be able to run the code sample.

# Replace values in a dictionary based on another dictionary

You can also use a for loop to replace the values in a dictionary based on another dictionary.

Copied!
my_dict = 'name': 'default', 'site': 'default', 'id': 1, 'topic': 'Python' > another_dict = 'name': 'bobby hadz', 'site': 'bobbyhadz.com' > for key, value in another_dict.items(): my_dict[key] = value # 👇️ # 'id': 1, 'topic': 'Python'> print(my_dict)

We used a for loop to iterate over the items of the second dictionary.

On each iteration, we replace the key-value pair of the first dictionary.

You can also check for the existence of the keys in the first dictionary.

Copied!
my_dict = 'name': 'default', 'site': 'default', 'id': 1, 'topic': 'Python' > another_dict = 'name': 'bobby hadz', 'site': 'bobbyhadz.com', 'abc': 'xyz', 'one': 'two', > for key, value in another_dict.items(): if key in my_dict: my_dict[key] = value # 👇️ # 'id': 1, 'topic': 'Python'> print(my_dict)

On each iteration, we use the in operator to check if the current key is contained in the dictionary.

The keys are only replaced if they exist in the first dictionary.

# Replace values in a dictionary using a dict comprehension

You can also use a dict comprehension to replace values in a dictionary.

Copied!
my_dict = 'name': 'default', 'site': 'default', 'id': 1, 'topic': 'Python' > another_dict = 'name': 'bobby hadz', 'site': 'bobbyhadz.com', 'abc': 'xyz', 'one': 'two', > my_dict = key: another_dict.get(key, value) for key, value in my_dict.items() > # # 'id': 1, 'topic': 'Python'> print(my_dict)

We used a dict comprehension to iterate over the dictionary’s items.

Dict comprehensions are very similar to list comprehensions.

They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.

On each iteration, we use the dict.get() method to get the value of the key in the second dictionary.

We specified the current value as a fallback in case the key doesn’t exist in the second dictionary.

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:

Name Description
key The key for which to return the value
default The default value to be returned if the provided key is not present in the dictionary (optional)
Copied!
another_dict = 'name': 'bobby hadz', 'site': 'bobbyhadz.com', 'abc': 'xyz', 'one': 'two', > print(another_dict.get('id')) # 👉️ None print(another_dict.get('topic')) # 👉️ None print(another_dict.get('name')) # 👉️ bobby hadz

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

# Additional Resources

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

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Change Dictionary Values in Python

Change Dictionary Values in Python

  1. Change Dictionary Values in Python Using the dict.update() Method
  2. Change Dictionary Values in Python Using the for Loop
  3. Change Dictionary Values in Python by Unpacking Dictionary Using the * Operator

This tutorial will look into multiple ways of changing the specific key’s value in the Python dictionary. We can do it by using the below methods,

Change Dictionary Values in Python Using the dict.update() Method

In this method, we pass the new key-value pairs to the update() method of the dictionary object. We can change one and more key-value pairs using the dict.update() method.

my_dict = < 'Khan': 4, 'Ali': 2, 'Luna': 6, 'Mark': 11, 'Pooja': 8, 'Sara': 1> print('Original:') print(my_dict)  my_dict.update('Khan': 6, 'Luna': 9>)  print('\nAfter update:') print(my_dict) 
Original: 'Khan': 4, 'Ali': 2, 'Luna': 6, 'Mark': 11, 'Pooja': 8, 'Sara': 1>  After update: 'Khan': 6, 'Ali': 2, 'Luna': 9, 'Mark': 11, 'Pooja': 8, 'Sara': 1> 

Change Dictionary Values in Python Using the for Loop

In this method, we keep iterating through the dictionary using the for loop until we find the key whose value needs to be modified. After getting the key, we can change the key’s value by assigning a new value to it.

my_dict = < 'Khan': 4, 'Ali': 2, 'Luna': 6, 'Mark': 11, 'Pooja': 8, 'Sara': 1>  for key, value in my_dict.items():  if key == 'Ali':  my_dictPython update all values in dict = 10  print(my_dict) 
'Khan': 4, 'Ali': 10, 'Luna': 6, 'Mark': 11, 'Pooja': 8, 'Sara': 1> 

Change Dictionary Values in Python by Unpacking Dictionary Using the * Operator

In this method, we can change the dictionary values by unpacking the dictionary using the * operator and then adding the one or more key-value pairs we want to change the dictionary.

my_dict = < 'Khan': 4, 'Ali': 2, 'Luna': 6, 'Mark': 11, 'Pooja': 8, 'Sara': 1> my_dict = < **my_dict, 'Pooja': 12> print(my_dict) 

Related Article — Python Dictionary

Copyright © 2023. All right reserved

Источник

Читайте также:  Python time from string
Оцените статью