Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gottadiveintopython/04fce1af28eb66d1053ff191f5b616ce to your computer and use it in GitHub Desktop.
Save gottadiveintopython/04fce1af28eb66d1053ff191f5b616ce to your computer and use it in GitHub Desktop.
[teratailの質問] 複数の特定のkeyを取り除いた辞書を作る効率的な方法
# https://teratail.com/questions/337003
unnecessary_keys = ('s', 'd', 't', 'step', 'duration', 'transition', )
intersection = set(unnecessary_keys).intersection
def method_1(d):
d = d.copy()
for key in unnecessary_keys:
d.pop(key, None)
return d
def method_2(d):
return {
key: value for key, value in d.items()
if key not in unnecessary_keys
}
def method_3a(d):
'''ppaulさんのmethod_3に少し手を加えた物'''
d = d.copy()
for key in intersection(d):
d.__delitem__(key)
return d
def method_3b(d):
'''method_3aの'd.__delitem__'をloopの外に出した物'''
d = d.copy()
delitem = d.__delitem__
for key in intersection(d):
delitem(key)
return d
def method_4a(d):
'''ppaulさんのmethod_4'''
d = d.copy()
for key in unnecessary_keys:
if key in d:
d.__delitem__(key)
return d
def method_4b(d):
'''method_4aの'd.__delitem__'をloopの外に出した物'''
d = d.copy()
delitem = d.__delitem__
for key in unnecessary_keys:
if key in d:
delitem(key)
return d
def method_5(d):
'''quickquipさんの方法'''
d = d.copy()
for key in unnecessary_keys:
if key in d:
del d[key]
return d
def method_6(d):
'''quickquipさんの方法'''
d = d.copy()
for key in intersection(d):
del d[key]
return d
sample_dict = {
'x': 100,
'y': 200,
'd': 10,
'transition': 'in_cubic',
}
assert method_1(sample_dict) == {'x': 100, 'y': 200, }
assert method_2(sample_dict) == {'x': 100, 'y': 200, }
assert method_3a(sample_dict) == {'x': 100, 'y': 200, }
assert method_3b(sample_dict) == {'x': 100, 'y': 200, }
assert method_4a(sample_dict) == {'x': 100, 'y': 200, }
assert method_4b(sample_dict) == {'x': 100, 'y': 200, }
assert method_5(sample_dict) == {'x': 100, 'y': 200, }
assert method_6(sample_dict) == {'x': 100, 'y': 200, }
from timeit import timeit
print('1 :', timeit(lambda: method_1(sample_dict)))
print('2 :', timeit(lambda: method_2(sample_dict)))
print('3a:', timeit(lambda: method_3a(sample_dict)))
print('3b:', timeit(lambda: method_3b(sample_dict)))
print('4a:', timeit(lambda: method_4a(sample_dict)))
print('4b:', timeit(lambda: method_4b(sample_dict)))
print('5 :', timeit(lambda: method_5(sample_dict)))
print('6 :', timeit(lambda: method_6(sample_dict)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment