Reputation: 171
How to reduce number of code when element does not already exist in dictionary? Otherwise assign it to the object. Prove of python concept:
class MyClass:
pass
key = "test python"
item = MyClass()
d = {}
if d.get(key) is None:
d[key] = item
else:
item = d[key]
print(item)
Is it possible to remove if else statement?
Upvotes: 0
Views: 123
Reputation: 36
You can read python documentation -> setdefault:
class MyClass:
pass
key = 'test python'
item = MyClass()
d = {}
item = d.setdefault(key, item)
It`s more pythonic!!!!
Upvotes: 1
Reputation: 193
Maybe see if using defaultdict
(from collections) would help?
I'm not sure exactly what you're trying to do, but I think this is the same behavior?
from collections import defaultdict
class MyClass:
pass
key = "test python"
item = MyClass()
d = defaultdict()
d[key] = item
print(item)
Unrelated, with the above, I think
if not key in d:
or
if not d.get(key):
might be a little more pythonic?
Upvotes: 1
Reputation: 2817
You can use dict.setdefault for this:
key = "test python"
item = MyClass()
d = {}
print(d.setdefault(key, item))
Upvotes: 1
Reputation:
Read up on Documentation before you start asking questions...
You want to use this setdefault(key[, default])
Upvotes: 1