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

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

    Comprehension could be also convenient in this case:

    # from a list
    keys = ["k1", "k2"]
    d = {k:None for k in keys}
    
    # or from another dict
    d1 = {"k1" : 1, "k2" : 2}
    d2 = {k:None for k in d1.keys()}
    
    d2
    # {'k1': None, 'k2': None}
    

提交回复
热议问题