Get name of dictionary

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

    Here's my solution for a descriptive error message.

    def dict_key_needed(dictionary,key,msg='dictionary'):
        try:
            value = dictionary[key]
            return value
        except KeyError:
             raise KeyError(f"{msg} is missing key '{key}'")
    

提交回复
热议问题