If the dict values need to be extended by another list, extend()
method of list
s may be useful.
a = {}
a.setdefault('abc', []).append(1) # {'abc': [1]}
a.setdefault('abc', []).extend([2, 3]) # a is now {'abc': [1, 2, 3]}
This can be especially useful in a loop where values need to be appended or extended depending on datatype.
a = {}
some_key = 'abc'
for v in [1, 2, 3, [2, 4]]:
if isinstance(v, list):
a.setdefault(some_key, []).extend(v)
else:
a.setdefault(some_key, []).append(v)
a
# {'abc': [1, 2, 3, 2, 4]}
- Append list elements without duplicates
If there's a dictionary such as a = {'abc': [1, 2, 3]}
and it needs to be extended by [2, 4]
without duplicates, checking for duplicates (via in
operator) should do the trick. The magic of get()
method is that a default value can be set (in this case empty set ([]
)) in case a key doesn't exist in a
, so that the membership test doesn't error out.
a = {some_key: [1, 2, 3]}
for v in [2, 4]:
if v not in a.get(some_key, []):
a.setdefault(some_key, []).append(v)
a
# {'abc': [1, 2, 3, 4]}