Get name of dictionary

后端 未结 6 1702
感情败类
感情败类 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:29

    The following doesn't work on standard dictionaries, but does work just fine with collections dictionaries and counters:

    from collections import Counter
    
    # instantiate Counter ditionary
    test= Counter()
    
    # create an empty name attribute field
    test.name = lambda: None
    
    # set the "name" attribute field to "name" = "test"
    setattr(test.name, 'name', 'test')
    
    # access the nested name field
    print(test.name.name)
    

    It's not the prettiest solution, but it is easy to implement and access.

提交回复
热议问题