user4637416
user4637416

Reputation:

Refer a value from a key which is in the form tuple of multiple elements

dic = {('UUU','UUC'):'F',('GUU','GUC','GUA','GUG'):'V'}
L =  ['UUU', 'GUG', 'GUU']

As you see each elements of list(L) are in dictionary as keys. Now i want to replace each elements of L by its corresponding values. Output would be:

output = ['F','V']

How can i do that?

Upvotes: 0

Views: 30

Answers (2)

Steve Barnes
Steve Barnes

Reputation: 28425

Using list compression:

In [1]:  dic = {('UUU','UUC'):'F',('GUU','GUC','GUA','GUG'):'V'}

In [2]:  L =  ['UUU', 'GUG', 'GUU']

In [3]:  list(set([v for k,v in dic.items() for x in L if x in k]))
Out [3]: ['V', 'F']

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 600059

One way would be to decompose the keys into individual elements, and create a new dict from those:

new_dic = {}
for k, v in dic.items():
    for sub_k in k:
        new_dic[sub_k] = v

Now it's a simple matter of looping through the list:

output = [new_dic[i] for i in L]

and you can de-duplicate with set:

output = list(set(output))

Upvotes: 1

Related Questions