Search code examples
python-dateutilrelativedelta

Python method to create a dateutil.relativedelta.relativedelta object from a dict


I'm using the following method to create the object stated in the title:

from dateutil import relativedelta

MA_dict = {'years': 0,
         'months': 0,
         'weeks': 0,
         'days': 1,
         'hours': 0,
         'minutes': 0,
         'seconds': 0}


def dict2relativedelta(dict):
    '''
    creates relativedelta variable that can be used to calculate dates
    '''
    dt = relativedelta.relativedelta(years=dict['years'], months=dict['months'], weeks=dict['weeks'], days=dict['days'],
                                     hours=dict['hours'], minutes=dict['minutes'], seconds=dict['seconds'])
    return dt

However, I would like to simplify this so that I can just pass

MA_dict = {'days': 1}

and the function will return the same. How can I do that?


Solution

  • You don't need a special function for this as Python has argument unpacking with the ** operator. You can accomplish what you want with:

    MA_dict = {"days": 1}
    rd = relativedelta.relativedelta(**MA_dict)