2

I have to make class objects with dictionaries inside. I can't figure out how to change values when making them. I can change them after, but same code doesn't work inside making line.

There are some attempts (#tells error from code below, i did't change anything other than machine1 making code):


#on this i get error: keyword cant be expression
class One():
    def __init__(self, problem):
        self.problem = {
            "year": 0,
            "model": 0,
            "stupidity": 0
            }
machine1 = One(problem[year]=1)



#TypeError: __init__() takes 2 positional arguments but 4 were given
class One():
    def __init__(self, problem):
        self.problem = {
            "year": 0,
            "model": 0,
            "stupidy": 0
            }
machine1 = One(1,1,1)



#does't change anything
class One():
    def __init__(self, problem):
        self.problem = {
            "year": 0,
            "model": 0,
            "stupidy": 0
            }
machine1 = One(1)
print(machine1.problem["year"])



#I can change it later with this
machine1.problem["year"] = 1
Pirita
  • 43
  • 5
  • Do you want to set values of dict in constructor? – Olvin Roght May 04 '19 at 17:38
  • It seems that your question sets out a number of ways that you want to initialize instances of your class. The last way: `machine1 = One(1)` seems to be intended to set the `"year"` key to `1`. Why should your `__init__()` method know that it is the `"year"` key that should be set and not the other keys? – quamrana May 04 '19 at 17:40
  • Possible duplicate of [How to merge two dictionaries in a single expression?](https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression) – quamrana May 04 '19 at 17:43
  • @quamrana strange dupe target, where do you see merging two dictionaries? – sanyassh May 04 '19 at 17:52
  • @Sanyash: In the very first example: The class has a`dict`, and it looks like the call site: `machine1 = One(problem[year]=1)` is an attempt to set one of the keys. In my head, in the general case, that is a merge of two dicts. See the answer from Ajax1234: https://stackoverflow.com/a/55985254 – quamrana May 04 '19 at 17:55

1 Answers1

3

You can use keyword arguments with dictionary unpacking:

class One:
  def __init__(self, **kwargs):
    self.problem = {"year": 0, "model": 0, "stupidity": 0, **kwargs}

one = One(year=1)

Now, the presence of any keys in kwargs will override its original key in self.problem:

print(one.problem['year'])

Output:

1

In turn:

one = One(year=1, model=1, stupidity = 1)
print(one.problem)

Output:

{'year': 1, 'model': 1, 'stupidity': 1}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102