0

Hi my goal is to convert the dictionary items in the form as commented below -

class MyClass:
    def __init__ (self, **kwargs):
        self.kwargs=kwargs

    def myfunc (self):
        sum=0
        for x in self.kwargs.items():
            sum+=x[1]
        return (sum)

d = {"k1": 1, "k2": 2, "k3": 3}  # to be converted  

ab=MyClass(k1=1, k2=2, k3=3) # so as to be accepted here
ab.myfunc()

Is there any particular operation to be done like here instead of print?

d = {"k1": 1, "k2": 2, "k3": 3}

for i,k in enumerate(d.keys()):
    for j,v in enumerate(d.values()):
        if i==j:
            print(k,v) # some operation to be done here instead of print?
        else:
            pass
Suvo
  • 67
  • 5
  • 3
    You mean `ab=MyClass(**d)`? – awesoon Sep 01 '18 at 08:19
  • Related: https://stackoverflow.com/questions/287085/what-do-args-and-kwargs-mean and https://stackoverflow.com/questions/2921847/what-does-the-star-operator-mean – abc Sep 01 '18 at 08:21

1 Answers1

2

You can directly pass dict d using ** operator operator while instantiating MyClass

d = {"k1": 1, "k2": 2, "k3": 3}
ab = MyClass(**d) 
Sunitha
  • 11,777
  • 2
  • 20
  • 23
  • Thanks. This is exactly what I wanted, this **d called something? just to google and learn more :) – Suvo Sep 01 '18 at 08:23
  • @Suvo [What does double star asterisk do for parameters](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) can help you out – Patrick Artner Sep 01 '18 at 08:25
  • Something like `Python asterisk unpacking` should work for a google search – N Chauhan Sep 01 '18 at 08:25
  • @Suvo I'm sure it's an example you've produced... but you realise that your entire thing is just `sum(some_dict.values())` ? (since it appears you're not concerned about anything to do with keys...?) – Jon Clements Sep 01 '18 at 08:39
  • 1
    @Suvo (eg - unless you have a need to be able to access them via keys... you might as well just pass the `dict` as an argument instead of unpacking it to arguments itself, and just have myfunc `return sum(self.dictionary_given.values())` kind of thing? (not much point unpacking a dictionary to arguments unless you're going to use them...) – Jon Clements Sep 01 '18 at 08:43
  • @Jon Clements: Yea you're correct, its just an example. My aim is to define number of players in black jack as key and after distributing cards to them the sum will store the values. – Suvo Sep 01 '18 at 08:46