-1

I want to create a new object of a certain class. I can do it this way:

user = Users(name=lst['name'],
             email=lst['email'],
             surname=lst['surname'])

lst is dictionary and each instance of lst could has diffrent fields. For example, it could look like this:

lst = {'name': 'John', 'email': 'john@mail.com', 'surname': 'Jang'}

but it can also look:

 lst = {'name': 'John', 'phone': '00000000'}

I want to make a function which will handle list as explained above. Is there exist a way to do it in python?

trojek
  • 3,078
  • 2
  • 29
  • 52
  • If all `lst` contains is those three keys, you can do `Users(**lst)`, which unpacks the `dict` into keyword arguments. – Izaak van Dongen Sep 18 '17 at 16:10
  • should not be reopened. Duplicate of https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters and many others – UmNyobe Sep 19 '17 at 08:22

1 Answers1

1

Just use some defaults, here I've used Nones but you could provide some sensible default value for each:

class User:
    def __init__(self, name=None, email=None, phone=None, surname=None):
        print(name, email, surname, phone)

ls = {'name': 'name1', 'surname': 'surname2'}

and then unpack ls during the call:

User(**ls)

which will assign any keys that exist in ls to their appropriate arguments. You might also want to ammend User.__init__ to grab any excess keyword arguments by using **kwargs in the function definition.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253