简体   繁体   中英

elegant way to fill dictionary with variables in python

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 ?

If the quotes are the problem, how about this?

fruit = 'apple'
vegetable = 'potato'

dic = dict(
    fruit = fruit,
    vegetable = vegetable
)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM