1

Building from How do I create a dictionary with keys from a list and values defaulting to (say) zero? and especially this answer:

How do I create a dictionary with keys from a list and values separate empty lists?
(Where, later on, I'll be able to append elements)

Community
  • 1
  • 1
Antonio
  • 18,335
  • 12
  • 89
  • 190

3 Answers3

14

Use dictionary comprehension,

{item: [] for item in my_list}

You are simply iterating the list and creating a new list for every key.

Alternatively, you can think about using collections.defaultdict, like this

from collections import defaultdict
d = defaultdict(list)
for item in my_list:
    d[item].append(whatever_value)

Here, the function object which we pass to defaultdict is the main thing. It will be called to get a value if the key doesn't exist in the dictionary.

thefourtheye
  • 221,210
  • 51
  • 432
  • 478
0

This is simple and easy implementation , It is self explaining , we iterate over all the elements in the list and create a unique entry in the dictionary for each value and initialize it with an empty list

sample_list = [2,5,4,6,7]
sample_dict = {}
for i in sample_list:
    sample_dict[i] = []
ZdaR
  • 20,813
  • 6
  • 58
  • 82
-1

By normal method:

>>> l = ["a", "b", "c"]
>>> d = {}
>>> for i in l:
...   d[i] = []
... 
>>> d
{'a': [], 'c': [], 'b': []}
>>> 

By using collections module

>>> l = ["a", "b", "c"]
>>> import collections
>>> d = collections.defaultdict(list)
>>> for i in l:
...   d[i]
... 
[]
[]
[]
>>> d
defaultdict(<type 'list'>, {'a': [], 'c': [], 'b': []})
Vivek Sable
  • 9,246
  • 3
  • 34
  • 50