0

Is there any function can give all keys of a dictionaries the value 0

8th Mar 2022, 1:05 PM
Chaimae EL GUENNOUNI
Chaimae EL GUENNOUNI - avatar
11 Answers
+ 7
Chaimae EL GUENNOUNI , # >>> this is when you create a new dict. you may do this with a dict comprehension like: value = 0 dict_ = {key:value for key in ["tom", "sue", "bob", "ann"]} print(dict_) # result: {'tom': 0, 'sue': 0, 'bob': 0, 'ann': 0} # >>>this is if you want to "reset" all values of an existing dict dict2 = {'tom': 7, 'sue': 4, 'bob': 0, 'ann': 2} value = 0 dict2 = {key:value for key in dict2} # result: {'tom': 0, 'sue': 0, 'bob': 0, 'ann': 0} # >>> or you can use fromkeys() dict3 = {'tom': 7, 'sue': 4, 'bob': 0, 'ann': 2} dict3 = dict3.fromkeys(dict3, 0) print(dict3)
8th Mar 2022, 7:14 PM
Lothar
Lothar - avatar
+ 2
Did you know that a dictionary can't have duplicate keys? Please tag a relevant language to improve clarity on discussion topic, by language. (Edit) Tags have been updated https://code.sololearn.com/W3uiji9X28C1/?ref=app
8th Mar 2022, 1:14 PM
Ipang
+ 2
Yes but I want the same values of all keys not the same keys in dict
8th Mar 2022, 1:16 PM
Chaimae EL GUENNOUNI
Chaimae EL GUENNOUNI - avatar
+ 2
You mean change all the values of a dictionary items to zero? Idk whether a function dedicated for that purpose existed. But if not, I guess you can always resort to updating items' value using a loop right?
8th Mar 2022, 1:21 PM
Ipang
+ 2
Chaimae EL GUENNOUNI, Provide a dictionary sample, and what result you expected. It helps us here to better understand the goal.
8th Mar 2022, 3:11 PM
Ipang
+ 1
It has method to get all keys ( dict.keys() ). Then you can filter keys which value to be zero or any then.
8th Mar 2022, 1:47 PM
Jayakrishna 🇮🇳
+ 1
What language do you use? Please add the language you use in the tags.
8th Mar 2022, 2:01 PM
sneeze
sneeze - avatar
+ 1
x.keys() // returns all the keys of x dictionary. Then use filter to get keys having value 0
8th Mar 2022, 2:16 PM
TOLUENE
TOLUENE - avatar
+ 1
Or if you just want all the values .values()
8th Mar 2022, 4:35 PM
Paul K Sadler
Paul K Sadler - avatar
+ 1
for k in d: d[k] = 0 # d dict.
8th Mar 2022, 10:05 PM
Per Bratthammar
Per Bratthammar - avatar
0
Is that impossible?!
8th Mar 2022, 1:16 PM
Chaimae EL GUENNOUNI
Chaimae EL GUENNOUNI - avatar