I have:
l = [{"a": 2}, {"a": 4}, {"a": 10}, {"a": 11}]
I need to multiply by 2 all "a" dict keys. So I would have:
l = [{'a': 4}, {'a': 8}, {'a': 20}, {'a': 22}]
I can do it by such code:
for i in l:
i.update({"a": 2 * i["a"]})
But it's ugly.
There should be nice Pythonic one-liner.
This is one liner code updating the dictionaries and returning the list. However, if dictionaries do not have a
key it raises KeyError
. And, all the dictionaries are updated until an exception occurs. I hope it helps but code readibility matters so simply updating dictionary in for loop does not cost much.
>>> l = [{"a": 2}, {"a": 4}, {"a": 10}, {"a": 11}]
>>> map(lambda x:(x,x.__setitem__("a",x["a"]*2))[0],l)
[{'a': 4}, {'a': 8}, {'a': 20}, {'a': 22}]
l = [{k:v*2} for d in l for k, v in d.items()]
This also takes into account if there actually is a key a
.
for d in l:
if 'a' in d:
d['a'] *= 2
Or
for d in l:
try:
d['a'] *= 2
except KeyError:
# No key `a`
pass
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.