I have a dictionary d
already created. I want to change only the values of a certain type. For example's sake, I want to replace strings with their lengths.
The boring way to do this is with a for loop:
for k,v in d.items():
if isinstance(v, str):
d[k] = len(v)
But isn't looping slow?
It can be done with a comprehension. I think this is equivalent to the above:
d = {k: len(v) if isinstance(v, str) else v for k,v in d.items()}
I tried it with a map, but these don't work (apparently because I don't understand something about tuple unpacking in Python 3):
d = dict(map(lambda k,v: (k, len(v) if isinstance(v, str) else v), d.items()))
d = dict(map(lambda (k,v): (k, len(v) if isinstance(v, str) else v), d.items()))
This seems to work, but it's getting big and ugly:
dict(map(lambda kv: (kv[0], len(kv[1]) if isinstance(kv[1], str) else kv[1]), d.items()))
It seems like this kind of operation would be common, but I can't find specific answers.
What's the correct, Pythonic, and performant way to do it?
You already have the answer, and CoryKramer already mentioned it.
d = {k: len(v) if isinstance(v, str) else v for k,v in d.items()}
This does it, and is the cleanest way.