1

I'm searching for an elegant more generic way to fill a dictionary with variables:

dic = {}
fruit = 'apple'
vegetable = 'potato'

dic['fruit'] = fruit
dic['vegetable'] = vegetable

is there a more generic way without using the variable-name in quotes ?

Egirus Ornila
  • 1,234
  • 4
  • 14
  • 39

2 Answers2

4

If the quotes are the problem, how about this?

fruit = 'apple'
vegetable = 'potato'

dic = dict(
    fruit = fruit,
    vegetable = vegetable
)
Niko Föhr
  • 28,336
  • 10
  • 93
  • 96
1

May not be a very elegant solution but you could use locals() for retrieving the variables and then convert them into a dictionary.

fruit = 'apple'
vegetable = 'potato'
dic = {key:value for key, value in locals().items() if not key.startswith('__')}

This results in {'vegetable': 'potato', 'fruit': 'apple'}

However, I believe a better option would be to pass the variable names and create a dictionary as provided in this answer:

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

dic = create_dict('fruit', 'vegetable')

Edit: Using eval() is dangerous. Please refer to this answer for more information.

Sudheesh Singanamalla
  • 2,283
  • 3
  • 19
  • 36
  • You really shouldn't be recommending using `eval`, *especially* when it is being used to evaluate input to a function. – user3483203 May 06 '18 at 06:29
  • Absolutely! Using `eval` is dangerous, I believe the answer I linked to which uses `eval` assumes that the input `i` is sanitized and checked before running through the `eval()` – Sudheesh Singanamalla May 06 '18 at 06:33