繁体   English   中英

试图在python中翻转字典,其中值是列表

[英]Trying to flip a dictionary in python where values are lists

我正在尝试使python中的这个字典被还原为具有值的键-例如。 值成为键。 值列表中的每个项目都应该有一个键。

anotations = {
    "epithelial_cell": [24,34,18,29,11,25,26,35,27,13,33,14,28,12,21,7,22,19,15,23,31,32,16,36],
    "fibroblastic_reticular_cell": [30],
    "endothelial_cell": [5,20,3],
    "pericyte": [40],
    "fibroblast": [8,4,6,10,17,39,0,1,2,38,9,37],
}

#make keys the numbers
anotations_op = {}
for cellName in anotations:
    for clusterNum in anotations[cellName]:
        anotations_op.update({clusterNum, cellName})

这是我得到的错误:

Traceback (most recent call last):
  File "main.py", line 13, in <module>
    anotations_op.update({clusterNum, k_v_pair[0]})
TypeError: cannot convert dictionary update sequence element #0 to a sequence

我会使用带有两个for循环的嵌套list理解:

>>> d = {'first': [1, 2, 3], 'second': [4, 5, 6]}
>>> {e: k for k, v in d.items() for e in v}
{1: 'first', 2: 'first', 3: 'first', 4: 'second', 5: 'second', 6: 'second'}

为简单起见,使用 2 个for循环:

anotations = {
    "epithelial_cell": [24,34,18,29,11,25,26,35,27,13,33,14,28,12,21,7,22,19,15,23,31,32,16,36],
    "fibroblastic_reticular_cell": [30],
    "endothelial_cell": [5,20,3],
    "pericyte": [40],
    "fibroblast": [8,4,6,10,17,39,0,1,2,38,9,37],
}

anotations_op = {}

for cell_name, cluster_nums in anotations.items():
    for cluster_num in cluster_nums:
        anotations_op[cluster_num] = cell_name

print(anotations_op)
# {24: 'epithelial_cell', 34: 'epithelial_cell', 18: 'epithelial_cell', 29: 'epithelial_cell', 11: 'epithelial_cell', 25: 'epithelial_cell', 26: 'epithelial_cell', 35: 'epithelial_cell', 27: 'epithelial_cell', 13: 'epithelial_cell', 33: 'epithelial_cell', 14: 'epithelial_cell', 28: 'epithelial_cell', 12: 'epithelial_cell', 21: 'epithelial_cell', 7: 'epithelial_cell', 22: 'epithelial_cell', 19: 'epithelial_cell', 15: 'epithelial_cell', 23: 'epithelial_cell', 31: 'epithelial_cell', 32: 'epithelial_cell', 16: 'epithelial_cell', 36: 'epithelial_cell', 30: 'fibroblastic_reticular_cell', 5: 'endothelial_cell', 20: 'endothelial_cell', 3: 'endothelial_cell', 40: 'pericyte', 8: 'fibroblast', 4: 'fibroblast', 6: 'fibroblast', 10: 'fibroblast', 17: 'fibroblast', 39: 'fibroblast', 0: 'fibroblast', 1: 'fibroblast', 2: 'fibroblast', 38: 'fibroblast', 9: 'fibroblast', 37: 'fibroblast'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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