Home > Enterprise >  Using **kwargs to assign dictionary keys values to a class instance
Using **kwargs to assign dictionary keys values to a class instance

Time:11-05

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?

CodePudding user response:

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)

CodePudding user response:

Yes, you can used kwargs, I think you are looking for the following code:

class Book:

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

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

        for key, value in kwargs.items():
            self.info[key] = value

CodePudding user response:

Nevermind, I just figured it out.

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

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

        for key, value in kwargs.items():
            self.info[key] = value

This should have been obvious in retrospect

  • Related