[英]How do i retrieve the variable name for each dict in a list of dicts?
我可能在這里缺少一些基本知識,但請考慮以下因素:
graph=nx.read_graphml('path here...')
dDict=dict(nx.degree_centrality(graph)) #create dict
lDict=dict(nx.load_centrality(graph))
new_lists=[dDict,lDict]
for i in new_lists:
print().... #how to get variable name i.e. dDict
我該如何遍歷字典列表,以便在執行打印時將變量名返回給我,即該字典等於我,即我希望能夠檢索回“ dDict”和“ lDict”?如
dDict ['name'] ='dDict'
有任何想法嗎..?
編輯:我想這樣做的原因是,這樣我就可以將這些集中度度量附加到具有新列名的數據框上,即:
for idx in range(len(new_lists)):
for i in range(len(df)):
rowIndex = df.index[i]
df.loc[rowIndex, idx] = new_lists[idx][rowIndex] #instead of idx how do i dynamically name the column according to the list item name.
您可以遍歷globals()
並獲取與您要查找的內容匹配的對象的變量名。
有關https://docs.python.org/3/library/functions.html?highlight=globals#globals的更多信息
但是,這是一個相當麻煩的把戲,您不應該這樣做! 而是,重新設計軟件,這樣您就不必首先查找變量名。
def get_var_name_of(x):
return [k for k,v in globals().items() if v==x][0]
dDict = {1:'asd'}
lDict = {2:'qwe'}
new_list=[dDict,lDict]
for d in new_list:
print(get_var_name_of(d))
dDict
lDict
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.