Search code examples
pythondictionaryinitializationinstancekeyword-argument

Using **kwargs to assign dictionary keys + values to a class instance


I'm trying to use **kwargs to create a dictionary inside an instance of a class. I want to hand my Book class two required variables(title and author) as well as a number of optional key/value pairs, and have it create an internal dictionary holding those keys and values. Here is my code:

class Book:
    
    def __init__(self, title, author, **kwargs):

        self.info = {
            'title': title,
            'author': author,
        }

For example, I'd like to hand Book an argument like year='1961' and have it set up a key/value pair ('year': '1961'). Up until now I've been using if/else statements for this, but that seems inefficient and ugly. Can I use **kwargs to do it?


Solution

  • kwargs can be treated as a dictionary and you can merge the two sets of data few different ways depending on your python version.

    3.9+:

    class Book:
        def __init__(self, title, author, **kwargs):
            self.info = {
                'title': title,
                'author': author,
            } | kwargs
    

    3.5+:

    class Book:
        def __init__(self, title, author, **kwargs):
            self.info = {
                'title': title,
                'author': author,
                **kwargs}
    

    <3.4:

    class Book:
        def __init__(self, title, author, **kwargs):
            self.info = {
                'title': title,
                'author': author,
            }
            self.info.update(kwargs)