Reputation: 15778
For a lot of objects before calling .append()
I do something like:
if not d.get('turns'):
d['turns'] = []
Is there a oneliner in Python to do this?
After some answers, here's my kind of code:
d = json.loads(str(self.data))
if not d.get('turns'):
d['turns'] = []
d['turns'].append({
'date': time_turn,
'data': data
})
Upvotes: 1
Views: 55
Reputation: 17263
You can use defaultdict
:
from collections import defaultdict
d = defaultdict(list)
d['turns'] # []
Other option is to use setdefault
:
d.setdefault('turns', []) # []
d.setdefault('turns', 'foo') # []
UPDATE Given the full code you could either write
d = defaultdict(list, json.loads(str(self.data)))
d['turns'].append({'date': time_turn, 'data': data})
or
d = json.loads(str(self.data))
d.setdefault('turns', []).append({'date': time_turn, 'data': data})
Upvotes: 4
Reputation: 78690
Is there a oneliner in Python to do this?
Yes
d.setdefault('turns', [])
Demo:
>>> d = {}
>>> d.setdefault('turns', [])
[] # the inserted value is also returned
>>> d
{'turns': []}
If the key is found, setdefault
behaves like get
:
>>> d['turns'].append(1)
>>> d.setdefault('turns', 'irrelevant')
[1]
Upvotes: 3
Reputation: 1603
depending on if the get is standard, it likely has the option to specify a default return if the item is not found, so
d.get('turns', [])
will give you the value if it exists, or [] if it doesn't.
Upvotes: 3
Reputation: 631
Well, you can "oneline" it using :
d['turns'] = [] if not d.get('turns')
Upvotes: 0