0
Is there any function can give all keys of a dictionaries the value 0
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)
+ 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
+ 2
Yes but I want the same values of all keys not the same keys in dict
+ 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?
+ 2
Chaimae EL GUENNOUNI,
Provide a dictionary sample, and what result you expected. It helps us here to better understand the goal.
+ 1
It has method to get all keys ( dict.keys() ). Then you can filter keys which value to be zero or any then.
+ 1
What language do you use? Please add the language you use in the tags.
+ 1
x.keys() // returns all the keys of x dictionary.
Then use filter to get keys having value 0
+ 1
Or if you just want all the values .values()
+ 1
for k in d: d[k] = 0 # d dict.
0
Is that impossible?!