簡體   English   中英

用python中的變量填充字典的一種優雅方法

[英]elegant way to fill dictionary with variables in python

我正在尋找一種用變量填充字典的更優雅的通用方法:

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

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

有沒有在引號中使用變量名的更通用的方法?

如果引號是問題,那怎么辦?

fruit = 'apple'
vegetable = 'potato'

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

可能不是一個很好的解決方案,但是您可以使用locals()檢索變量,然后將其轉換為字典。

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

結果為{'vegetable': 'potato', 'fruit': 'apple'}

但是,我相信一個更好的選擇是傳遞變量名並創建一個字典,如以下答案所示

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

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

編輯:使用eval()是危險的。 請參考此答案以獲取更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM