Reputation: 634
Say I have this dictionary:
my_dicts = {'key1': 'true', 'key2': 'true'}
and I want to replace true with True
How could I do that.
I've tried to do:
for t in my_dicts:
t.update((k, "True") for k, v in t.items() if v == "true")
But I get this error:
AttributeError: 'str' object has no attribute 'update'
Upvotes: 0
Views: 114
Reputation: 1245
Another approach is to use json.loads to convert string to bool type.
import json
my_dicts = {'key1': 'true', 'key2': 'true'}
for key, value in my_dicts.items():
if value == 'true':
my_dicts[key] = json.loads(value)
print(my_dicts)
Output:
{'key1': True, 'key2': True}
Upvotes: 1
Reputation: 57
Without modifying your code too much, here is my suggestion:
my_dicts = {'key1': 'true', 'key2': 'true'}
for key in my_dicts:
if my_dicts[key] == 'true': my_dicts[key] = 'True'
print("After:")
for key, value in my_dicts.iteritems():
print(key + " = " + my_dicts[key])
Upvotes: 1
Reputation: 11476
You can use a dict comprehension:
>>> {key: True if value == 'true' else value for key, value in my_dicts.items()}
{'key1': True, 'key2': True}
Other answers mention using dict.update
, if you go this route, there's no need to build the complete dictionary again, you just need to replace the keys for which value == 'true'
:
>>> my_dicts.update({key: True for key, value in my_dicts.items() if value == 'true'})
>>> my_dicts
{'key1': True, 'key2': True}
Upvotes: 2
Reputation: 731
Francisco's answer is good -- it's how i would do it.
For another inline solution that modifies the dictionary inline rather than create a new one (which would be useful if the dictionary is huge):
d.update((k, v if v != 'true' else True) for k,v in d.items())
Upvotes: 2
Reputation: 155333
As Francisco notes, a dict
comprehension will work to make a new dict
with replaced keys. You can also just modify the dict
in place, either with an explicit loop:
for k, v in my_dicts.items():
if v == 'true':
my_dicts[k] = True
or by using the dict
comprehension and updating the original dict
with the result:
my_dicts.update({k: True if v == 'true' else v for k, v in my_dicts.items()})
The first approach is likely faster in general, since it avoids the temporary dict
, and doesn't even try to update keys unless the value is the "true"
string you want to replace.
To be clear, it's normally unsafe to modify a dict
as you iterate it, so you're excused if you worry about the first loop. But in this case, it's fine; the danger with mutating a dict
as you iterate it comes from adding or removing keys, but since every key you set already exists in the dict
, you're only updating the value of an existing key (which is safe/legal), not changing the set of keys themselves (which will bite you).
Upvotes: 1