chippycentra
chippycentra

Reputation: 879

Get the key from a specific value in a dictionary in Python

I have a dictionary such as:

task_list
[['Genus', {'Genus1': ['Sp1_A'], 'Genus2': ['Sp2_A', 'Sp2_B']}], ['Family', {'Family1': ['Sp1_A'], 'Family2': ['Sp2_A', 'Sp2_B']}], ['SubFamily', {'SubFamily1': ['Sp1_A'], 'SubFamily1': ['Sp2_A', 'Sp2_B']}], ['Order', {'Order': ['Sp2_A', 'Sp2_B', 'Sp1_A']}]]

so here is the content:

>>> for i in task_list:
...     print(i)
... 
['Genus', {'Genus1': ['Sp1_A'], 'Genus2': ['Sp2_A', 'Sp2_B']}]
['Family', {'Family1': ['Sp1_A'], 'Family2': ['Sp2_A', 'Sp2_B']}]
['SubFamily', {'SubFamily1': ['Sp1_A'], 'SubFamily2': ['Sp2_A', 'Sp2_B']}]
['Order', {'Order': ['Sp2_A', 'Sp2_B', 'Sp1_A']}]

And I have a tree file where I can print :

>>> for leaf in tree:
...     print(leaf.name)
... 
YP_001.1
Sp2_A
YP_002.1
YP_003.1
Sp1_A
YP_004.1
YP_005.1
Sp2_B
Sp2_A

As you can see Sp1_A Sp2_A and Sp1_B (with Sp1_A present twice) are all in the values of the dic:

And I would like for each leaf.name, to add a tag with the following command : leaf.add_features(tag=tag) where tag should be the GenusNumber from the task_list

So here :

for leaf in tree:
    tag=the corresponding `key` of the `value` in the `dic`
    leaf.add_features(tag=tag)
    print(tag)

I should get:

Genus2 (corresponding to Sp2_A from task_list key)
Genus1 (corresponding to Sp1_A from task_list key)
Genus2 (corresponding to Sp2_B from task_list key)
Genus2 (corresponding to Sp2_A from task_list key)

Thank you for your help

Upvotes: 0

Views: 55

Answers (2)

ramazan polat
ramazan polat

Reputation: 7910

I think your data structure is wrong. As far as I understand, your array elements have a relationship which is can be pointed by dictionaries. Array elements should not have a relationship.

In you example, task_list[0][0] is the key of task_list[0][1]. You can define it as as dict:

genus = {'Genus1': ['Sp1_A'], 'Genus2': ['Sp2_A', 'Sp2_B']}

If you have more than one key like genus, you can also embed it in a dict:

task_list = {'Genus': {'Genus1': ['Sp1_A'], 'Genus2': ['Sp2_A', 'Sp2_B']},
             'Family': {'Family1': ['Sp1_A'], 'Family2': ['Sp2_A', 'Sp2_B']},
             ...}

If you do this, then it will be much more easy to program what you want:

for root_key, root_val in task_list.items():
    print(root_key) # Genus

    for child_key, child_val in root_val.items(): # '{'Genus1': ['Sp1_A'], 'Genus2': ['Sp2_A', 'Sp2_B']}'
        print(child_key, child_val) # Genus1, ['Sp1_A']

Upvotes: 1

Austin
Austin

Reputation: 26057

You can iterate over 'Genus' dictionary checking for the value and retrieve the key:

for leaf in tree:
    tag = None
    for k, v in task_list[0][1].items():
        if leaf.name in v:
            tag = k
    if tag:
        leaf.add_features(tag=tag)
        print(tag)

Upvotes: 1

Related Questions