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?
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.
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.
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.
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')))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With