[英]create dictionary from list of variables
我正在尋找一種無需明確寫入鍵即可創建字典的方法我想創建獲取數字變量的函數,並創建字典,其中變量名稱是鍵,它們的值是變量值
而不是編寫以下函數:
def foo():
first_name = "daniel"
second_name = "daniel"
id = 1
return {'first_name':first_name, 'second_name':second_name}
我想用函數得到相同的結果:
create_dict_from_variables(first_name, second_name)
無論如何要這樣做嗎?
你不能不寫至少變量名,但可以這樣寫速記:
>>> foo = 1
>>> bar = 2
>>> d = dict(((k, eval(k)) for k in ('foo', 'bar')))
>>> d
{'foo': 1, 'bar': 2}
或作為一個函數:
def createDict(*args):
return dict(((k, eval(k)) for k in args))
>>> createDict('foo','bar')
{'foo': 1, 'bar': 2}
您還可以使用globals()
而不是eval()
:
>>> dict(((k, globals()[k]) for k in ('foo', 'bar')))
您可以使用locals
,但我建議您不要使用它。 明確地做。
>>> import this
[...]
Explicit is better than implicit.
[...]
如果你明確地這樣做,你的代碼通常會更好、更可預測、更不容易被破壞並且更容易理解。
原則上,這可以通過將變量名稱傳遞給函數create_dict
,然后使用模塊inspect
從create_dict
函數內部到達調用者堆棧幀來實現。
不,沒有,因為 Python 函數無法獲取有關用於調用該函數的變量的信息。 另外,想象一下做這樣的事情:
create_dict_from_variables(first_name[:-3] + "moo", last_name[::2])
該函數將無法知道用於創建參數的表達式。
pip install sorcery
from sorcery import dict_of
a = 1
b = 2
c = 3
d = dict_of(a, b, c)
print(d)
# {'a': 1, 'b': 2, 'c': 3}
這個問題有一個有趣的解決方案,它不涉及外部庫。 但是,需要稍微不同的語法: eval(f(a,b))
# Auxiliary Function
f = lambda s: f"dict({ ','.join( f'{k}={k}' for k in s.split(',') ) })"
first_name = "daniel"
second_name = "joe"
D = eval(f('first_name,second_name'))
print(D)
# {'first_name': 'daniel', 'second_name': 'joe'}
在上面的示例中,OP 的主要目標仍然完成,因為我們只需鍵入一次變量的名稱即可創建字典。 但是,語法仍然有點冗長。
附注。 上面代碼的一個重要好處是我們在其原始命名空間中評估字典,這消除了與函數范圍(globals()、locals() 等)有關的任何限制。 這是我使用這種方法的主要動機。
其實有一個辦法:
from varname import nameof
def foo(first_name,second_name):
return {nameof(first_name):first_name, nameof(second_name):second_name}
first_name = "daniel"
second_name = "daniel"
print (foo(first_name,second_name))
輸出:
{'first_name': 'daniel', 'second_name': 'daniel'}
您可以在下面獲得python-varname
包:
https://github.com/pwwang/python-varname
基本用途:
from varname import nameof
s = 'Hey!'
print (nameof(s))
輸出:
s
你不可以做這個。
您的函數可以定義為:
def create_dict_from_variables(first_name, second_name):
return something_from(first_name, second_name)
你可以調用這個函數:
create_dict_from_variables('abcd', 'efgh')
這兩個參數'abcd'
和'efgh'
不是命名變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.