【问题标题】:How do i retrieve the variable name for each dict in a list of dicts?如何检索字典列表中每个字典的变量名称?
【发布时间】:2019-06-06 08:52:25
【问题描述】:

我可能在这里遗漏了一些基本的东西,但请考虑以下几点:

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. 

【问题讨论】:

  • 至少每个字典也可能被其他几个标识符引用,或者没有。这不是对象的属性。您能否提供一些背景信息 - 为什么您想这样做?您可能还会发现 this article 很有用。
  • 缩进关闭。为什么“for i in new_lists:”是缩进的?您能否提供一个工作示例来说明您的问题/问题?还有什么是“nx”,是否缺少导入?
  • 简而言之:你没有。你需要像{'dDict': dDict} 这样的东西来保存这些信息。
  • Python 变量只是引用。任何给定对象都没有一个名称,有 1 到 N 个引用,其中一些可能有名称,而另一些则没有。如果您在列表中创建字典,则根本没有名称。如果您需要字典名称,请使用字典来存储它们。

标签: python python-3.x list loops dictionary


【解决方案1】:

您可以遍历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

【讨论】:

  • 当我运行上面我得到错误: AttributeError: 'dict' object has no attribute 'reindex'
  • 您使用的 Python 版本是什么?另外,哪一行给你错误?因为我发布的代码在 Python3.7 中完美运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多