简体   繁体   中英

Create a Dictionary with List Values through a Dict Comprehension?

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.

字典理解中的键和值不表示为元组,它们只是用分隔:

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

你是这个意思吗

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM