如何迭代字典的值?

2024-07-05 14:25:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本有键和值对的字典。每个键可以有多个值,例如字典可以是这样的:

    enh_166084:['AC002454.1', 'RN7SL7P']
    enh_341666:['MYOM1', 'RP13-270P17.2', 'SNORA70']

现在,我想对键进行迭代,并将其对应的值写入一个txt文件,每一个值都在一行上,类似这样的东西:

    AC002454.1
    RN7SL7P
    MYOM1
    RP13-270P17.2
    ......

我该怎么做?你知道吗


Tags: 文件txt字典对键有键enhsnora70rp13
3条回答

使用dictionaryitervalues()方法:

for value in your_dict.itervalues():
    # Since the values are lists, we have to enumerate those too:
    for item in value:
        output_file.write(item)
        output_file.write("\n")

遍历每个键,然后遍历每个值:

for key in dictionary: # For each key
    for value in dictionary[key]: # For each value in the dictionary under that key
        # Do something with the value

也许您可以将值提取为嵌套列表,将其展平,然后在其上循环:

import itertools
chain = itertools.chain(*mydict.values())
for i in list(chain):
    output_file.write(item)
    output_file.write("\n")

相关问题 更多 >