繁体   English   中英

从Python中的字典中的特定值获取密钥

[英]Get the key from a specific value in a dictionary in Python

我有一本字典,例如:

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

所以这里是内容:

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

我有一个树文件可以在其中打印:

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

如您所见, Sp1_A Sp2_ASp1_B (其中Sp1_A出现两次)都在dic的值中:

我想为每个leaf.name使用以下命令添加tagleaf.add_features(tag=tag) ,其中tag应该是GenusNumber中的task_list

所以在这里 :

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

我应该得到:

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)

谢谢您的帮助

您可以遍历'Genus'字典检查值并检索密钥:

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)

我认为您的数据结构有误。 据我了解,您的数组元素具有一种可以由字典指出的关系。 数组元素不应该有关系。

在您的示例中, task_list[0][0]task_list[0][1] 您可以将其定义为dict

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

如果您有多个类之genus键,也可以将其嵌入dict

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

如果这样做,那么编程所需的内容将更加容易:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM