2

Let's say I have

a = [1,2,3,4,5]

I'm trying to create a dictionary where

dictObj = { (key,[]) for key in a}

but I'm getting an unhashable type error. This seems weird to me since it's fine if values are lists right? I was wondering if anyone could tell me the correct syntax for creating a hash table where all the keys are the elements in a and each key points to an empty array.

6
  • That's not how you do a dictionary comprehension. Commented Feb 25, 2018 at 8:37
  • Whats your expected output? Commented Feb 25, 2018 at 8:38
  • And your title should say dictionary comprehension, not list comprehension Commented Feb 25, 2018 at 8:39
  • @VivekKalyanarangan. That's stated quite clearly in the question. Commented Feb 25, 2018 at 8:40
  • 1
    Why not just use collections.defaultdict(list)? Commented Feb 25, 2018 at 8:44

3 Answers 3

5

The key and value in a dictionary comprehension aren't represented as a tuple, they are simply separated by a :

dictObj = {key:[] for key in a}
Sign up to request clarification or add additional context in comments.

Comments

3

Do you mean this?

dictObj = { key:[] for key in a}

Comments

3

If you want to keep what you have, you need to wrap dict() instead of curly brackets:

dict((key, []) for key in a)

which is the same as what others have given, but just slightly different syntax.

Aditionally, if you want to initialize your dictionary with empty lists, you should have a look at collections.defaultdict, which initializes your keys to any type you choose. This prevents you from having to do this yourself.

Here is an example usage:

from collections import defaultdict

d = defaultdict(list)
a = [1,2,3,4,5]

for key in a:
    print(key, ':', d[key])

Which prints out an initialized list for each item, as outputted below:

1 : []
2 : []
3 : []
4 : []
5 : []

Then you could add items to each key from here.

Comments

Your Answer

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.