I need to know the fastest way of getting a copy of a dictionary without a specific key.
I have a dict
like this:
users = {
1: {'state': 'apple', 'menu_id': 123, 'args':['some data']},
2: {'state': 'something', 'menu_id': 321},
3: {'state': 'banana', 'menu_id': 666, 'args':['trash', 'temporary']}
}
I need to get a copy of users
without 'args'
key
I've solved this problem in three ways and there are my 3 solutions:
Solution 1:
s = users.copy()
for k,v in s.items():
v.pop('args', None)
Solution 2:
s = {k: {'state': v['state'], 'menu_id':v['menu_id']} for k,v in users.items()}
Solution 3:
s = {k: {p: q for p,q in v.items() if p != 'args'} for k, v in users.items()}
Which solution is faster or are there any other faster ways to get the expected result?
for k,v in obj.items(): v.pop('args', None)
will mutate sub-dicts in original structure.Even if performance should not bother you until you'll face performance problems, but anyway, considering 3rd one as base:
deepcopy
is magnitude slower than 3rd one