-1

One of the coolest things I've learned about python recently is that a dictionary can take parameters like this:

dict(red=3,blue=2,yellow=5)

How could I make a function that takes arguments in the same fashion and pass them to a dictionary? I don't want to declare red, blue, or yellow as individual parameters. Ideally, this would take in named parameters of any kind.

I've already tried:

def foo(*args):

...and it doesn't like how the parameters are named.

Another thought I had was extending the dictionary definition so I could still use init of the dictionary, but I wouldn't know how to do that either.

KemptCode
  • 34
  • 6

1 Answers1

0

I think you were on the right track with *args, but what I think you want to use is **kwargs.

def make_dict(**kwargs):
    return dict(**kwargs)

myDict = make_dict(red=2, cyan=43)
print(myDict)

it should print {'red': 2, 'cyan': 43}

Josh Anibal
  • 146
  • 5