Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dictionary from list of variables

I'm looking for a way to create a dictionary without writing the key explicitly. I want to create a function that gets the number of variables and creates a dictionary where the variable names are the keys and their values are the variable values.

Instead of writing the following function:

def foo():     first_name = "daniel"     second_name = "daniel"     id = 1     return {'first_name':first_name, 'second_name':second_name} 

I want to get the same result with function :

create_dict_from_variables(first_name, second_name) 

Is there any way to do so?

like image 417
Idok Avatar asked Feb 29 '12 07:02

Idok


People also ask

Can you convert a list into a dictionary?

To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

How do you convert a variable to a dictionary?

To convert Python Set to Dictionary, use the fromkeys() method. The fromkeys() is an inbuilt function that creates a new dictionary from the given items with a value provided by the user. Dictionary has a key-value data structure. So if we pass the keys as Set values, then we need to pass values on our own.

How do you create a dictionary from a list of keys and values?

Using zip() with dict() function The simplest and most elegant way to build a dictionary from a list of keys and values is to use the zip() function with a dictionary constructor.


2 Answers

You can't do it without writing at least the variable names, but a shorthand can be written like this:

>>> foo = 1 >>> bar = 2 >>> d = dict(((k, eval(k)) for k in ('foo', 'bar'))) >>> d {'foo': 1, 'bar': 2} 

or as a function:

def createDict(*args):      return dict(((k, eval(k)) for k in args))  >>> createDict('foo','bar') {'foo': 1, 'bar': 2} 

you can also use globals() instead of eval():

>>> dict(((k, globals()[k]) for k in ('foo', 'bar'))) 
like image 150
Not_a_Golfer Avatar answered Oct 07 '22 15:10

Not_a_Golfer


You can use locals, but I would recommend against it. Do it explicitly.

>>> import this [...] Explicit is better than implicit. [...] 

Your code will generally be better, more predictable, less prone to breaking and more comprehensible if you do it explicitly.

like image 29
Chris Morgan Avatar answered Oct 07 '22 17:10

Chris Morgan