112

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.

codegeek
33.5k12 gold badges65 silver badges65 bronze badges
asked Nov 19, 2013 at 18:53
5
  • 1
    Why do you want to initialize keys? Commented Nov 19, 2013 at 18:54
  • 8
    There is no such thing as a key without a value in a dict. You can just set the value to None, though. Commented Nov 19, 2013 at 18:54
  • What does it mean to define a key with no value? If you try to access that item, would it generate an error (as if you had never defined that key), or yield something (in which case that something is its value)? Commented Nov 19, 2013 at 19:01
  • Since you know you're going to replace the values later, it really doesn't matter what you set them to. Commented Nov 19, 2013 at 19:02
  • I was creating a dictionary that goes through another dictionary to only grab the values of the keys I wanted so I wanted to be able to compare keys and then set them if they are equal. Might of been a bad way but it works! Thanks again! Commented Nov 19, 2013 at 19:12

8 Answers 8

137

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)
ohmu
19.8k44 gold badges114 silver badges151 bronze badges
answered Nov 19, 2013 at 19:00
Sign up to request clarification or add additional context in comments.

1 Comment

When using dict.fromkeys(..., default_value), make sure default_value is not of a type that requires a constructor (like list), else you'll get references to the same object in all your buckets.
75

You could initialize them to None.

aga
29.6k13 gold badges91 silver badges127 bronze badges
answered Nov 19, 2013 at 18:55

4 Comments

Or if None is a legitimate value for one or more of your key-value tuples, you can use something like "SENTINEL = object()" and use SENTINEL as your sentinel value, testing with "is" instead of "==".
Yep agreed, Look at your overall scope of data and determine what value should never be available ever. -1, false, none, random int, random string and so on.. Old question but top result still.
Using None will result in a 'NoneType' object does not support item assignment error...
@Markus: Such an error would occur when trying to do something like Definition[key] = something when Definition is None (which is not what is being advocated here), not when Definition[key] is None (which is).
12

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)
answered Nov 19, 2013 at 18:58

Comments

9

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))
answered Jul 28, 2014 at 23:01

Comments

6

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}
answered Jun 25, 2020 at 10:45

Comments

5

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
answered Nov 19, 2013 at 19:00

Comments

2
q = input("Apple")
w = input("Ball")
Definition = {'apple': q, 'ball': w}
answered Jan 10, 2017 at 23:58

Comments

0

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.

answered Mar 18, 2014 at 0:35

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.