Fini
Fini

Reputation: 173

Get values (within a set) from dictionary within dictionary

I have looked at these already, but no luck so far stackquestion1 stackquestion2 stackquestion3 and many many others. It always seems to be different?

I really think it is a simple solution, but I have been trying for hours now. I want to get the values of a nested dictionary, within a for loop. I have a simplified example here:

def write_to_file(class_set, clusterdict, outfile):
with open(outfile, "w") as outputfile:
    writer = csv.writer(outputfile, delimiter='\t')
    class_list = list(class_set)
    header = ["\t"] + class_list
    writer.writerow(header)  # write header
    for organism, cluster in clusterdict.items():
        #print clusterdict.get(organism) # works, just to see if it does anything
        line = []
        #some stuff here that works, writing specific lines
        #part that doesnt work
        line.append(clusterdict.get(organism).get(cluster)) # gives TypeError: unhashable type: 'dict'
        line.append(clusterdict.get(organism) # does work, but of course gives me the wrong dict values
        writer.writerow(line)

The dict looks like this. Its a dictionary with multiple organisms and withing that a dictionary with multiple clusters. So each organism has multiple clusters, with (sometimes multiple) sets as values (I think the problem might be the sets?)

clusterdict = 
'organism1':{'cluster1': [set(['value1', 'value2']) , [set(['value3', 'value4'])], 'cluster2: [set(['value5', 'value6']) , [set(['value7', 'value8'])]} , 
'organism2':{.......} , 
'organism3':{.......} , etc

I tried many many ways to get the values. For example like dict[key1][key2], but this also gives me the "unhashable" error. Can someone give me some directions?

Upvotes: 0

Views: 52

Answers (1)

Mike Scotty
Mike Scotty

Reputation: 10782

You are trying to use cluster as a key, but actually cluster is your value, and it's also a dictionary.

You can iterate over cluster just as you did with your main dictionary:

for organism, cluster in clusterdict.items():
    for key, value in cluster.items():
        ...

They error TypeError: unhashable type: 'dict' came from the fact that keys have to be hashable, and cluster is a dictionary - which is not hashable.

But then again, you don't want to use cluster as a key, because cluster is your value, just that your value is also a dict with keys and values.

Upvotes: 1

Related Questions