【发布时间】:2019-07-21 01:08:45
【问题描述】:
我已经看过这些了,但到目前为止还没有运气 stackquestion1 stackquestion2 stackquestion3 和许多其他人。好像总是不一样?
我真的认为这是一个简单的解决方案,但我已经尝试了几个小时。我想在 for 循环中获取嵌套字典的值。我在这里有一个简化的例子:
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)
字典看起来像这样。它是一个包含多个生物的字典,并且包含一个具有多个集群的字典。所以每个有机体都有多个集群,以(有时是多个)集合作为值(我认为问题可能出在集合上?)
clusterdict =
'organism1':{'cluster1': [set(['value1', 'value2']) , [set(['value3', 'value4'])], 'cluster2: [set(['value5', 'value6']) , [set(['value7', 'value8'])]} ,
'organism2':{.......} ,
'organism3':{.......} , etc
我尝试了很多方法来获取这些值。例如像dict [key1] [key2],但这也给了我“不可散列”的错误。谁能给我一些指示?
【问题讨论】:
-
你的变量
cluster是字典。您正在尝试将其用作密钥。如果您想遍历cluster的键和值,只需执行您对clusterdict( ->for key, value in cluster.items():) 所做的操作。旁注:为什么要将列表转换为列表?集合是无序的数据结构,它们可能会改变列表项的顺序。您应该考虑提供minimal reproducible example,并且还应该在您的问题中列出预期的输出。 -
我认为我的“clusterdict”是我的字典,我在 clusterdict.items() 中用于键、值,但我将它们命名为有机体和集群而不是键和值
-
clusterdict是一个字典,它包含的值也是字典。这是完全有效的。 -
但是“有机体”也是字典吗?但是那个确实有效
-
完全正确 ;)
for key, value in cluster.items()
标签: python python-2.7 dictionary set typeerror