简体   繁体   English

在python中逐步浏览字典中的项目

[英]Step through items in dictionary in python

I have a dictionary like so: 我有这样的字典:

{'AAAGGG': ['AGAGAGAA', 'AGAGAGAG'], 'AAAGGC': ['AGAGAGAG']})

I want to step through each key and then step through the chars of its corresponding values. 我想逐步浏览每个键,然后逐步浏览其对应值的字符。 So something like this: 所以像这样:

for key in myDict:
    for eachValue in key:
        for char in eachValue:
            do something

Hopefully there is an easy way of doing this. 希望有一个简单的方法可以做到这一点。

Python Tutorial: Looping Techniques Python教程:循环技术

When you have the key, use the key to look up the value. 当您拥有密钥时,请使用密钥来查找值。 Don't iterate through the key. 不要遍历密钥。

for key in myDict:
    for eachValue in myDict[key]:
        for char in eachValue:
            do something

More efficiently, iterate through the items and avoid the extra lookup: 更有效地,遍历项目并避免额外的查找:

for key, value in myDict.items():
    for eachValue in value:
        for char in eachValue:
            do something

This should do it: 应该这样做:

my_dict = {'AAAGGG': ['AGAGAGAA', 'AGAGAGAG'], 'AAAGGC': ['AGAGAGAG']})

for parent_value in my_dict.values():
    for sub_value in parent_value:
        for char in sub_value:
            do_something(char)

You're looking for chain.from_iterable : 您正在寻找chain.from_iterable

from itertools import chain
print list(chain.from_iterable({'long_key': ["abc", "cdef"], 'another_key':['ZYC', 'hgt']}.keys()))
#  ['a', 'n', 'o', 't', 'h', 'e', 'r', '_', 'k', 'e', 'y', 'l', 'o', 'n', 'g', '_', 'k', 'e', 'y']

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

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