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

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': , 'ball': }

and then later i can set them:

Definition[key] = something

I only want to initialize keys but I don't know the corresponding values until I have to set them later. Basically I know what keys I want to add the values as they are found. Thanks.

This question is related to python dictionary initialization key

The answer is


q = input("Apple")
w = input("Ball")
Definition = {'apple': q, 'ball': w}

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}

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)

You can initialize the values as empty strings and fill them in later as they are found.

dictionary = {'one':'','two':''}
dictionary['one']=1
dictionary['two']=2

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)

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.


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))

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python

Examples related to initialization

"error: assignment to expression with array type error" when I assign a struct field (C) How to set default values in Go structs How to declare an ArrayList with values? Initialize array of strings Initializing a dictionary in python with a key value and no corresponding values Declare and Initialize String Array in VBA VBA (Excel) Initialize Entire Array without Looping Default values and initialization in Java Initializing array of structures C char array initialization

Examples related to key

How do I check if a Key is pressed on C++ Map<String, String>, how to print both the "key string" and "value string" together Python: create dictionary using dict() with integer keys? SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch How to get the stream key for twitch.tv How to get key names from JSON using jq How to add multiple values to a dictionary key in python? Initializing a dictionary in python with a key value and no corresponding values How can I sort a std::map first by value, then by key?