Python: get value from dictionary when key is a list

Question:

I have a dictionary where the key is a list

cfn = {('A', 'B'): 1, ('A','C'): 2 , ('A', 'D'): 3}
genes = ['A', 'C', 'D', 'E']

I am trying to get a value from the dictionary if the gene pairs in the key exist in a list together. My attempt is as follows, however I get TypeError: unhashable type: 'list'

def create_networks(genes, cfn):
    network = list()
    for i in range(0, len(genes)):
        for j in range(1, len(genes)):
            edge = cfn.get([genes[i], genes[j]],0)
            if edge > 0:
                network.append([genes[i], genes[j], edge])

desired output:

network = [['A','C', 2], ['A', 'D', 3]]

solution based on comments and answer below: edge = cfn.get((genes[i], genes[j]),0)

Asked By: keenan

||

Answers:

Your keys in cfn are of type tuple as a key needs to be a hashable type.

Hashable types are immutable data types such as:

  • int
  • string
  • tuple
  • frozenset

as they can’t be changed or mutated. Otherwise you can’t access the value stored at that key.

So in your case you just need to change these [] into this ():

def create_networks(genes, cfn):
    network = list()
    for i in range(0, len(genes)):
        for j in range(1, len(genes)):
            # Use () to create a tuple
            edge = cfn.get((genes[i], genes[j]),0)
            if edge > 0:
                network.append([genes[i], genes[j], edge])
    return network

That way you don’t get the error and get your expected result of

>>> create_networks(genes, cfn)
[['A', 'C', 2], ['A', 'D', 3]]
Answered By: Wolric

You can do something like so:
https://onecompiler.com/python2/3yp8xepzp

cfn = {'AB': 1, 'AC': 2 , 'AD': 3}
genes = ['A', 'C', 'D', 'E']

def create_networks(genes, cfn):
    network = []
    for i in range(0, len(genes)):
        for j in range(1, len(genes)):
          keyy = genes[i]+''+genes[j]
          if keyy in cfn.keys():
            edge2 = cfn[genes[i]+''+genes[j]]
            if edge2 > 0:
                network.append([genes[i], genes[j], edge2])
    return network

print(create_networks(genes,cfn))
Answered By: Tirth
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.