Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dictionary where keys are variable names

I quite regularly want to create a dictionary where keys are variable names. For example if I have variables a and b I want to generate: {"a":a, "b":b} (typically to return data at the end of a function).

Are there any (ideally built in) ways in python to do this automatically? i.e to have a function such that create_dictionary(a,b) returns {"a":a, "b":b}

like image 316
kyrenia Avatar asked Oct 02 '16 15:10

kyrenia


2 Answers

Have you considered creating a class? A class can be viewed as a wrapper for a dictionary.

# Generate some variables in the workspace
a = 9; b = ["hello", "world"]; c = (True, False)

# Define a new class and instantiate
class NewClass(object): pass
mydict = NewClass()

# Set attributes of the new class
mydict.a = a
mydict.b = b
mydict.c = c

# Print the dict form of the class
mydict.__dict__
{'a': 9, 'b': ['hello', 'world'], 'c': (True, False)}

Or you could use the setattr function if you wanted to pass a list of variable names:

mydict = NewClass()
vars = ['a', 'b', 'c']
for v in vars: 
    setattr(mydict, v, eval(v)) 

mydict.__dict__
{'a': 9, 'b': ['hello', 'world'], 'c': (True, False)}
like image 107
p-robot Avatar answered Sep 28 '22 04:09

p-robot


You can write your own function for create_dict

def create_dict(*args):
  return dict({i:eval(i) for i in args})

a = "yo"
b = 7
print (create_dict("a", "b"))

Which gives {'a': 'yo', 'b': 7} output.
Here's a simple generator for the same:

vars = ["a", "b"]
create_dict = {i:eval(i) for i in args}

or you can use this one-liner lambda function

create_dict = lambda *args: {i:eval(i) for i in args}
print (create_dict("a", "b"))

But if you want to pass the variables to the function instead of the variable name as string, then its pretty messy to actually get the name of the variable as a string. But if thats the case then you should probably try using locals(), vars(), globals() as used by Nf4r

like image 27
lycuid Avatar answered Sep 28 '22 05:09

lycuid