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
5
  • Do you want to set values of dict in constructor? Commented May 4, 2019 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? Commented May 4, 2019 at 17:40
  • Possible duplicate of How to merge two dictionaries in a single expression? Commented May 4, 2019 at 17:43
  • @quamrana strange dupe target, where do you see merging two dictionaries? Commented May 4, 2019 at 17:52
  • @Sanyash: In the very first example: The class has adict, 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: stackoverflow.com/a/55985254 Commented May 4, 2019 at 17:55

1 Answer 1

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.