You do not need to call d.keys(), so
if key not in d:
d[key] = value
is enough. There is no clearer, more readable method.
You could update again with dict.get(), which would return an existing value if the key is already present:
d[key] = d.get(key, value)
but I strongly recommend against this; this is code golfing, hindering maintenance and readability.
Answer from Martijn Pieters on Stack OverflowYou do not need to call d.keys(), so
if key not in d:
d[key] = value
is enough. There is no clearer, more readable method.
You could update again with dict.get(), which would return an existing value if the key is already present:
d[key] = d.get(key, value)
but I strongly recommend against this; this is code golfing, hindering maintenance and readability.
Use dict.setdefault():
>>> d = {'key1': 'one'}
>>> d.setdefault('key1', 'some-unused-value')
'one'
>>> d # d has not changed because the key already existed
{'key1': 'one'}
>>> d.setdefault('key2', 'two')
'two'
>>> d
{'key1': 'one', 'key2': 'two'}
Made a class or plugin or whatever to append dict lists that may or may not exist.
dict[new_key].append(value)
wouldn't just create a list of there wasn't one and
dict[new_key] = []
Just clears the list.
I'm very new at this so maybe there is a way to do it in one line already, but I couldn't find it.
If you couldn't, now you can.
class Dict:
def init(self):
self.dict = {}
def append(self, key, value):
if key not in self.dict:
self.dict[key] = []
self.dict[key].append(value)
dict = Dict() dict.append(key, value)
You are looking for collections.defaultdict (available for Python 2.5+). This
from collections import defaultdict
my_dict = defaultdict(int)
my_dict[key] += 1
will do what you want.
For regular Python dicts, if there is no value for a given key, you will not get None when accessing the dict -- a KeyError will be raised. So if you want to use a regular dict, instead of your code you would use
if key in my_dict:
my_dict[key] += 1
else:
my_dict[key] = 1
I prefer to do this in one line of code.
my_dict = {}
my_dict[some_key] = my_dict.get(some_key, 0) + 1
Dictionaries have a function, get, which takes two parameters - the key you want, and a default value if it doesn't exist. I prefer this method to defaultdict as you only want to handle the case where the key doesn't exist in this one line of code, not everywhere.