简体   繁体   中英

Python Return Unpacked Dictionary

I would like to return an unpacked dictionary based on some condition:

def process(batch, cond):
  if(cond):
    return **batch
  else
    return batch

input = process(batch, cond)
output = model(input)

However, I get a SyntaxError: invalid syntax because of the return **batch line.

You can't. You need to extract your unpack logic to outside of process :

def process(batch):
    return batch

input = process(batch)
if cond:
    output = model(**input)
else:
    output = model(input)

If you really need process , also pass model to it:

def process(batch, model, cond):
    input = process(batch)
    if cond:
        return model(**input)
    return model(input)

output = process(batch, model, cond)

If I understand correctly, you could achieve what you want like this:

def process(batch, cond):
  if(cond):
    kwargs = batch
  else:
    kwargs = {'a': batch}
  return kwargs

def model(a=0, b=0, c=0):
  print(a + b + c)

batch = {'a': 100, 'b': 101, 'c': 102}
cond = True
kwargs = process(batch, cond)
model(**kwargs)
# Output: 303

batch = 100
cond = False
kwargs = process(batch, cond)
model(**kwargs)
# Output: 100

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM