在Python中从字典中的特定值获取键

2024-06-24 13:07:50 发布

您现在位置: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(sp1u出现两次)都在dic的值中:

我想为每个leaf.name添加一个tag命令:leaf.add_features(tag=tag),其中tag应该是task_list中的GenusNumber

所以这里:

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)

谢谢你的帮助


Tags: tokeyinfromtasktagorderlist
2条回答

我认为你的数据结构是错误的。 据我所知,你的数组元素有一个关系,可以通过字典来指出。数组元素不应具有关系

在您的示例中,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']

您可以遍历'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)

相关问题 更多 >