Search code examples
pythondictionarycoding-stylerefactoring

How to reduce number of python code?


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?


Solution

  • You can read python documentation -> setdefault:

    class MyClass:
        pass
    
    key = 'test python'
    item = MyClass()
    d = {}
    item = d.setdefault(key, item)
    

    It`s more pythonic!!!!