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

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

    Based on the clarifying comment by @user2989027, I think a good solution is the following:

    definition = ['apple', 'ball']
    data = {'orange':1, 'pear':2, 'apple':3, 'ball':4}
    my_data = {}
    for k in definition:
      try:
        my_data[k]=data[k]
      except KeyError:
        pass
    print my_data
    

    I tried not to do anything fancy here. I setup my data and an empty dictionary. I then loop through a list of strings that represent potential keys in my data dictionary. I copy each value from data to my_data, but consider the case where data may not have the key that I want.

提交回复
热议问题