[英]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.