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

前端 未结 8 1906
情深已故
情深已故 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:15

    Use the fromkeys function to initialize a dictionary with any default value. In your case, you will initialize with None since you don't have a default value in mind.

    empty_dict = dict.fromkeys(['apple','ball'])
    

    this will initialize empty_dict as:

    empty_dict = {'apple': None, 'ball': None}
    

    As an alternative, if you wanted to initialize the dictionary with some default value other than None, you can do:

    default_value = 'xyz'
    nonempty_dict = dict.fromkeys(['apple','ball'],default_value)
    
    0 讨论(0)
  • 2021-01-30 20:18

    You could initialize them to None.

    0 讨论(0)
提交回复
热议问题