7
votes

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}

4
"a":a doesn't make much sense, a is going to get replaced by its value. - Dimitris Fasarakis Hilliard
While there are certainly ways to do this (using locals()), I think this is very rarely a good solution. In the example you gave (returning multiple values from a function), consider returning a namedtuple from the collections module. - flornquake
@AnttiHaapala A place where one may use this regularly is in Django context data that gets passed to html templates. It makes sense to have {"a":a, "b":b} where the variable names in your views are the same as in the templates. - Daniel Holmes
Does this answer your question? create dictionary from list of variables - pfabri

4 Answers

9
votes

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)}
6
votes

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

1
votes

Have you tried something like:

a, b, c, d = 1, 2, 3, 4
dt = {k:v for k, v in locals().items() if not k.startswith('__')}
print(dt)
{'a': 1, 'd': 4, 'b': 2, 'c': 3}
0
votes

Extending on the code of @Nf4r, I use something like:

a, b = 1, 2

def make_dict(*args):
    # Globals will change of size, so we need a copy
    g = {k: v for k, v in globals().items() if not k.startswith('__')}  

    result = {}
    for arg in args:
        for k, v in g.items():
            try:
                if v == arg:
                    result[k] = v
            except ValueError:
                continue  # objects that don't allow comparison

    return result

make_dict(a, b)