Skip to content Skip to sidebar Skip to footer

How Do I Create A Dictionary With Keys From A List And Values Separate Empty Lists?

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

Solution 1:

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.

Solution 2:

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] = []

Solution 3:

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': []})

Post a Comment for "How Do I Create A Dictionary With Keys From A List And Values Separate Empty Lists?"