-2

I can achieve this with

mydict = {}
for a in range(0,6):
    mydict[a] = []

print (mydict)

#{0: [], 1: [], 2: [], 3: [], 4: [], 5: []}

Question is how would I achieve this with dict comprehension?

Edit:

d = {level: [] for level in range(1, level + 1)}

for each_level in d:
    d[each_level] = [ExampleClass(1, 1)
                         for _ in range(5)]

Sorry for not putting up what I had from the beginning, I thought it would not be much help.

This is what I have and it does what I want it to be but I am wondering if there is a way I can shorten all of this into one line or so.

In the end, I would like something like:

d = {level: [] for level in range(1, level + 1), [ExampleClass(1, 1) for _ in range(5)]
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 3
    Explaining the downvotes to you: The question is clear, but you could have tried some dict comprehensions yourself and explained where the problem was. – timgeb Oct 16 '18 at 18:22
  • 1
    Sorry about that. I have edited the OP –  Oct 16 '18 at 18:54

1 Answers1

4

Like this:

d = {a:[] for a in range(6)}

Don't use the name dict for your own variables, you will shadow the built in name dict.
Also note that if you don't supply the start argument to range, it defaults to 0.

You might also want to look into the defaultdict from the collections module instead of initializing a dict with empty lists yourself. Demo:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d[0]
[]
>>> d[1]
[]

The lists are only instantiated when you access a key for the first time.

>>> d
defaultdict(<class 'list'>, {0: [], 1: []})

edit: ~follow up~

I don't have your example class, but you should be able to learn the necessary synatx from this demo. slice will step in for your ExampleClass.

>>> ExampleClass = slice
>>> d = {a:[ExampleClass(1, 1) for _ in range(5)] for a in range(6)}
>>> d
{0: [slice(1, 1, None), slice(1, 1, None), slice(1, 1, None), slice(1, 1, None), slice(1, 1, None)], 1: [slice(1, 1, None), slice(1, 1, None), slice(1, 1, None), slice(1, 1, None), slice(1, 1, None)], 2: [slice(1, 1, None), slice(1, 1, None), slice(1, 1, None), slice(1, 1, None), slice(1, 1, None)], 3: [slice(1, 1, None), slice(1, 1, None), slice(1, 1, None), slice(1, 1, None), slice(1, 1, None)], 4: [slice(1, 1, None), slice(1, 1, None), slice(1, 1, None), slice(1, 1, None), slice(1, 1, None)], 5: [slice(1, 1, None), slice(1, 1, None), slice(1, 1, None), slice(1, 1, None), slice(1, 1, None)]}
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • How can I go one step foward and run a for loop for my values as well? –  Oct 16 '18 at 18:20
  • @Pikachu I don't quite understand the follow up question. Can you salvage your question by including a [MCVE], please? – timgeb Oct 16 '18 at 18:27
  • @Pikachu: Do you want something like this: `d = {a:list(range(1, 4)) for a in range(6)}`? – Matthias Oct 16 '18 at 18:29
  • @DeepSpace Yes I did and i edited the OP. sorry about that. –  Oct 16 '18 at 18:54