2

I would like tuple (foo, bar) where

 foo = 1
 bar = 2

be converted to,

foo_dict = {'foo' : foo, 'bar' : bar}

Is there an easy way to do it?

Update:

I see that my original post is quite misleading. So, considering foo and bar are local variables within a function scope. I'd like them to be saved to a global dictionary where the keys are their variable names.

Re-update: Thanks everyone for the attention. I was using ipywidgets.interact to tune some parameters (passed as value), however I would like to save them globally, say in a dictionary. That's why the question comes in. Maybe for downvoters there may seem pointless to do such conversion, but do please share some hints for solve my needs pythonically.

11
  • 1
    A tuple contains values, not variables. There is absolutely no connection between those values and the variables that held them; indeed, the value might never have been held in a variable at all, or might have been held by multiple variables. Commented Apr 27, 2017 at 16:08
  • @jasonharper I see, forgiving tuple, how could we do so for several variables then? If we have a dozen? Commented Apr 27, 2017 at 16:10
  • What is the bigger problem? Commented Apr 27, 2017 at 16:11
  • Actually I think this can be done, I just have to put the pieces together. I'm currently testing. Commented Apr 27, 2017 at 16:12
  • @MeadowMuffins Why do you need the foo_dict? Commented Apr 27, 2017 at 16:12

1 Answer 1

1

The required function call is

def func(**kwargs):
    for key in kwargs.keys():
        globals()[key]=kwargs[key]
    return kwargs

foo_dict = func(foo = 1, bar = 2)
print(foo_dict)
print(foo)
print(bar)

#{'bar': 2, 'foo': 1}
#56
#hehe
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, I've just got this far too. Problem solved. I guess I posted a bad question.

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.