我有一个包含键和值对的字典。每个键可以有多个值,例如字典可以是这样的:
enh_166084:['AC002454.1', 'RN7SL7P']
enh_341666:['MYOM1', 'RP13-270P17.2', 'SNORA70']
现在,我想迭代键并将其相应的值写入txt文件,每个值在一行上,如下所示:
AC002454.1
RN7SL7P
MYOM1
RP13-270P17.2
......
我该怎么做?
答案 0 :(得分:3)
使用字典itervalues()
方法:
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")
答案 1 :(得分:2)
迭代每个键,然后遍历每个值:
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
答案 2 :(得分:0)
也许您可以将值提取为嵌套列表,展平它,然后循环它:
import itertools
chain = itertools.chain(*mydict.values())
for i in list(chain):
output_file.write(item)
output_file.write("\n")