Home > Blockchain >  update a tuple key in dictionary with another dictionary in python
update a tuple key in dictionary with another dictionary in python

Time:05-26

I have:

edge_mask = {(0, 2): 0.7, (0, 6): 0.4}

and this:

labels: {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G'}

I need to update the dictionary:

edge_mask = {('A', 'C'): 0.7, ('A', 'G'): 0.4}

CodePudding user response:

Try:

edge_mask = {(0, 2): 0.7, (0, 6): 0.4}
labels = {0: "A", 1: "B", 2: "C", 3: "D", 4: "E", 5: "F", 6: "G"}

edge_mask = {(labels[a], labels[b]): v for (a, b), v in edge_mask.items()}
print(edge_mask)

Prints:

{('A', 'C'): 0.7, ('A', 'G'): 0.4}

CodePudding user response:

Try this:

edge_mask = {(0, 2): 0.7, (0, 6): 0.4}
labels = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G'}
  
{(labels[i], labels[j]):v for (i,j), v in edge_mask.items()}
# {('A', 'C'): 0.7, ('A', 'G'): 0.4}

or

from operator import itemgetter
{itemgetter(*k)(labels):v for k,v in edge_mask.items()}
  • Related