-1
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.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
David
  • 27
  • 5
  • 1
    [Asterisks in Python: what they are and how to use them](https://treyhunner.com/2018/10/asterisks-in-python-what-they-are-and-how-to-use-them/) (First hit when I sought for `python documentation asterisk`) – Some programmer dude Sep 10 '22 at 03:52

1 Answers1

0

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 **

l.b.vasoya
  • 1,188
  • 8
  • 23