Initializing a dictionary in python with a key value and no corresponding values

前端 未结 8 1908
情深已故
情深已故 2021-01-30 19:29

I was wondering if there was a way to initialize a dictionary in python with keys but no corresponding values until I set them. Such as:

Definition = {\'apple\':         


        
8条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-30 20:08

    you could use a defaultdict. It will let you set dictionary values without worrying if the key already exists. If you access a key that has not been initialized yet it will return a value you specify (in the below example it will return None)

    from collections import defaultdict
    your_dict = defaultdict(lambda : None)
    

提交回复
热议问题