如何传递字典的名称

时间:2015-02-09 10:00:51

标签: python

在下面的代码块中,我想传输一个字典的名称(result_dict)而不是内容。

def define_var(dictionary, entry, counter):
  for i in range(counter):
    print "reason%d = %s['%s_%d']" % (i + 1, dictionary, entry, counter)

当我调用函数时:

define_var(result_dict, 'start', 3)

打印:

  

reason1 = {'start_2':'test2','start_3':'test3','start_1':'test1'} ['start_1']

但我想打印出来:

  

reason1 = result_dict [start_1]

     

reason2 = result_dict [start_2]

等等

1 个答案:

答案 0 :(得分:0)

你可以在globals中找到对象:

def define_var(dictionary, entry, counter):
    d_name = next(k for k, v in globals().items() if v  is  dictionary)
    for i in range(counter):
        print("reason%d = %s['%s_%d']" % (i + 1, d_name, entry, counter))

print(define_var(result_dict, 'start', 3))


reason1 = result_dict['start_3']
reason2 = result_dict['start_3']
reason3 = result_dict['start_3']  

当您传入print(id(result_dict))时,如果您在print(id(dictionary))result_dict     您将看到它们都是具有相同ID的同一对象,因此我们只需使用isglobal dict获取名称。

如果要将结果分配给原因变量,可以将其返回,例如:

def define_var(dictionary, entry, counter):
    d_name = next(k for k, v in globals().items() if v is dictionary)
    return "%s['%s_%d']" % (d_name, entry, counter)

reason  = define_var(result_dict,2,3)
print(reason)

或使用词典:

def define_var(dictionary, entry, counter):
    d_name = next(k for k, v in globals().items() if v  is  dictionary)
    reasons = {}
    for i in range(counter):
        reasons["reason{}".format(i)] = "{}[{}]".format(d_name, entry)
    return reasons