Get name of dictionary

后端 未结 6 1714
感情败类
感情败类 2021-02-13 22:19

I find myself needing to iterate over a list made of dictionaries and I need, for every iteration, the name of which dictionary I\'m iterating on.

Here\'s an MWE (the co

6条回答
  •  感情败类
    2021-02-13 22:54

    Don't use a dict_list, use a dict_dict if you need their names. In reality, though, you should really NOT be doing this. Don't embed meaningful information in variable names. It's tough to get.

    dict_dict = {'dict1':dict1, 'dicta':dicta, 'dict666':dict666}
    
    for name,dict_ in dict_dict.items():
        print 'the name of the dictionary is ', name
        print 'the dictionary looks like ', dict_
    

    Alternatively make a dict_set and iterate over locals() but this is uglier than sin.

    dict_set = {dict1,dicta,dict666}
    
    for name,value in locals().items():
        if value in dict_set:
            print 'the name of the dictionary is ', name
            print 'the dictionary looks like ', value
    

    Again: uglier than sin, but it DOES work.

提交回复
热议问题