I want to insert a key-value pair into dict if key not in dict.keys(). Basically I could do it with:
if key not in d.keys(): d[key] = value
Use dict.setdefault():
>>> d = {1: 'one'} >>> d.setdefault(1, '1') 'one' >>> d # d has not changed because the key already existed {1: 'one'} >>> d.setdefault(2, 'two') 'two' >>> d {1: 'one', 2: 'two'}