Reputation: 2670
Say I have a list of dicts:
ls = [{'id': 1, 'a1': 2, 'a2': 3}, {'id':2, 'a2':4}, {'id':3, 'a2':5}]
where a1
doesn't exist in some dicts
I want to set a1
to 0 in these dicts where a1
is missing and change the key name a1
to b1
in all dicts. Here is the code I come up with
for l in ls:
l.setdefault('a1', 0)
l['b1'] = l.pop('a1')
I'm wondering is it possible to make it more efficient, as I need to run this piece of code millions of times. Any improvements would be appreciated.
Upvotes: 1
Views: 285
Reputation: 87074
Here is a slight improvement which exploits the fact that dict.pop()
can take an argument to return as the default if the key is not in the dictionary:
ls = [{'id': 1, 'a1': 2, 'a2': 3}, {'id':2, 'a2':4}, {'id':3, 'a2':5}]
for d in ls:
d['b1'] = d.pop('a1', 0)
>>> ls
[{'a2': 3, 'id': 1, 'b1': 2}, {'a2': 4, 'id': 2, 'b1': 0}, {'a2': 5, 'id': 3, 'b1': 0}]
Upvotes: 6