Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Replace All Values in a Dictionary

Is it possible to replace all values in a dictionary, regardless of value, with the integer 1?

Thank you!

like image 478
user1620716 Avatar asked Oct 18 '12 18:10

user1620716


People also ask

How do you overwrite a dictionary value in Python?

Append values to a dictionary using the update() method The Python dictionary offers an update() method that allows us to append a dictionary to another dictionary. The update() method automatically overwrites the values of any existing keys with the new ones.

Can we use Replace in dictionary Python?

To replace words in a string using a dictionary: Use a for loop to iterate over the dictionary's items. Use the str. replace() method to replace words in the string with the dictionary's items.

How do you replace a value in a nested dictionary Python?

Adding or updating nested dictionary items is easy. Just refer to the item by its key and assign a value. If the key is already present in the dictionary, its value is replaced by the new one. If the key is new, it is added to the dictionary with its value.

How do you replace a value in a DataFrame based on a dictionary?

You can use df. replace({"Courses": dict}) to remap/replace values in pandas DataFrame with Dictionary values. It allows you the flexibility to replace the column values with regular expressions for regex substitutions.


2 Answers

Sure, you can do something like:

d = {x: 1 for x in d}

That creates a new dictionary d that maps every key in d (the old one) to 1.

like image 131
Greg Hewgill Avatar answered Sep 23 '22 07:09

Greg Hewgill


You can use a dict comprehension (as others have said) to create a new dictionary with the same keys as the old dictionary, or, if you need to do the whole thing in place:

for k in d:
    d[k] = 1

If you're really fond of 1-liners, you can do it in place using update:

d.update( (k,1) for k in d )
like image 42
mgilson Avatar answered Sep 21 '22 07:09

mgilson