简体   繁体   中英

Coercing Dict to Read List as Tuples

I have an existing dict that has keys but no values. I would like to populate the values by iterating over two lists at the same time like so:

for (pair,name) in enumerate(zip([[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]], ['pair1','pair2','pair3','pair4','pair5','pair6'])):
    my_dict[tuple(name)] = pair

However I get the error: unhashable type: list.

So it seems my attempt to cast the list as a tuple doesn't work. I choose tuple because, according to what I read from other posts is a better way to go.

Can someone adjust this method to work as desired? I'm also open to other solutions.

Update

I will take the blame for not putting my whole function in the post. I thought being more concise would make things easier to understand, but in the end some important details were overlooked. Sorry for that. I'm working with numpy and sklearn Here is my whole function:

pair_names = ['pair1','pair2','pair3','pair4','pair5','pair6']
pair_dict = {p:[] for p in pair_names}
for (pair,key) in zip([[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]], ['pair1','pair2','pair3','pair4','pair5','pair6']):
    x = iris.data[:,pair]
    y = iris.target
    clf = DecisionTreeClassifier().fit(x,y)
    decision_boundaries = decision_areas(clf,[0,7,0,3])
    pair_dict[key] = decision_boundaries

Going on the suggestions from the answers to this question so far, I removed enumerate and simply used zip . Unfortunately, now on the line clf = DecisionTreeClassifier().fit(x,y) I get an error:number of samples does not match number of labels. Which I find odd, because I didnt change the sample size at all. My only guess is it has something to do with enumerate or zip -- because that is the only difference from the original function from the documentation example

也许您想要的是:

{ tuple(x):y for (x,y) in zip([[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]], ['pair1','pair2','pair3','pair4','pair5','pair6'])}

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