简体   繁体   中英

Trying to flip a dictionary in python where values are lists

I am trying to make it so that this dictionary in python is reverted the key with value - eg. with the values becoming the keys. There should be a key for each item in the value list.

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})

This is the error that I am getting:

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

I would use a nested list comprehension with two for loops:

>>> 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'}

Use 2 for loops for simplicity:

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'}

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