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

前端 未结 8 1904
情深已故
情深已故 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 19:59

    It would be good to know what your purpose is, why you want to initialize the keys in the first place. I am not sure you need to do that at all.

    1) If you want to count the number of occurrences of keys, you can just do:

    Definition = {}
    # ...
    Definition[key] = Definition.get(key, 0) + 1
    

    2) If you want to get None (or some other value) later for keys that you did not encounter, again you can just use the get() method:

    Definition.get(key)  # returns None if key not stored
    Definition.get(key, default_other_than_none)
    

    3) For all other purposes, you can just use a list of the expected keys, and check if the keys found later match those.

    For example, if you only want to store values for those keys:

    expected_keys = ['apple', 'banana']
    # ...
    if key_found in expected_keys:
        Definition[key_found] = value
    

    Or if you want to make sure all expected keys were found:

    assert(all(key in Definition for key in expected_keys))
    

提交回复
热议问题