pythonargument-unpacking

Why do I need '**' when loading json (Python)


t1 = Tournament("Aeroflot Open", 2010)
json_data = json.dumps(t1.__dict__)
print(json_data)

t = Tournament(**json.loads(json_data)) # <-------------------
print(f"name = {t.name}, year = {t.year}")

Could someone explain me why do I need these two asterisks ** when loading the json back. The line is above.


Solution

  • In Python, there is unpacking of the iterator using * and unpacking of the dictionary using **.

    Let's understand it with examples.

    
    # here is the class
    class Tournament:
    
      def __init__(self, name, age):
         self.name = name
         self.year = year 
    
    # here is init data in your case json.loads will
    data = {
      "name": "IPL",
      "year": 13
    }
    

    python will assign the key as a argument name and value as argument value like {"name": "IPL", "year": 13} the Tournament(name="IPL", year=13)

    tournament = Tournament(**data)
    print(f"name = {tournament.name}, year = {tournament.year}")
    

    Either you can directly assign the data, like

    tournament = Tournament(name="IPL", year=13)
    print(f"name = {tournament.name}, year = {tournament.year}")
    
    

    For more understanding, follow this * and **