Is it possible to flip the dictionary like a keyword factor?

Asked 2 years ago, Updated 2 years ago, 111 views

Is it possible to flip the dictionary like a keyword factor?

d = dict(param='test')

def f(param):
    print param

f(d)

Output:

{'param': 'test'} 

Now my code is running like this, but I just want to make test output. Take dict like a keyword factor

d = dict(p1=1, p2=2)
def f2(p1,p2):
    print p1, p2
f2(d)

I want to print it out like this, but how can I make it like this?

function dictionary python keyword

2022-09-21 18:19

1 Answers

So you want p1 and p2 of dict(p1=1,p2=2) to go straight into the f2(p1,p2) factors of p1 and p2

Then, when calling a function, you can use the ** operator before dict. In Python, it is called unpacking and more information is found in Unpacking Argument List.

d = dict(p1=1, p2=2)
def f2(p1,p2):
    print p1, p2
f2(**d)


2022-09-21 18:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.