1

I want to initialize a dictionary in python when I only have the keys and not the values - The values will come later in the code.

I thought about to do something like this:

dict = {}
for key in key_list:
    dict[key] = None

The question is if this is a good practice for this problem or do you have a better recommendation?

Shaked Eyal
  • 123
  • 1
  • 14

3 Answers3

4

You can do this with the fromkeys method:

# As noted in comments, fromkeys is a staticmethod on the dict class and will return a dict instance
d = dict.fromkeys(list(range(10)))

d
{0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}

To more directly address the point:

list_of_keys = ['o1', 'o2']

d = dict.fromkeys(list_of_keys)
{'o1': None, 'o2': None}
C.Nivs
  • 12,353
  • 2
  • 19
  • 44
  • 3
    No need to create the list, `fromkeys` will iterate on its own, and there is no need to create `d` since `fromkeys` is a staticmethod. `dict.fromkeys(range(10))` – DeepSpace Apr 10 '19 at 14:32
  • @DeepSpace I left it as a `list` to be directly applicable to what OP is asking for, *can I create a dict from a list of keys*, rather than could it be created from any iterable – C.Nivs Apr 10 '19 at 14:36
  • And if I have specific keys and not numbers? for example, I have something like this: `{'o1': None, 'o2': None}` – Shaked Eyal Apr 10 '19 at 14:37
  • @ShakedEyal it would take the same structure: `dict.fromkeys(['o1', 'o2', ...])` – C.Nivs Apr 10 '19 at 14:38
  • 2
    @C.Nivs But OP already has a list, so a better example (if we follow your argument) would be `dict.fromkeys(key_list)` – DeepSpace Apr 10 '19 at 14:38
  • @DeepSpace true, I've added in a more direct example – C.Nivs Apr 10 '19 at 14:40
  • Thank you for your help – Shaked Eyal Apr 10 '19 at 14:41
1

If your keys are already in memory, assuming an iterable object, then:

d = {key:None for key in keys}

It is the same as your posted code, just condensed.

SEpapoulis
  • 96
  • 3
0
dict.fromkeys([1, 2, 3, 4])

You can try that class method.

Mr.Robot
  • 333
  • 1
  • 2
  • 13