どうやってネストされた辞書をPythonで反復処理するのか

再帰と反復を使い分けてネストした辞書を走査することができます。ここでは一般的な2つの方法を説明します。

  1. 再帰的メソッド:
def traverse_dict(d):
    for key, value in d.items():
        if isinstance(value, dict):
            traverse_dict(value)
        else:
            print(key, ":", value)

# 示例字典
dict1 = {
    'name': 'Alice',
    'age': 25,
    'address': {
        'street': '123 Main St',
        'city': 'New York',
        'state': 'NY'
    }
}

# 调用函数
traverse_dict(dict1)

結果は出力済み

name : Alice
age : 25
street : 123 Main St
city : New York
state : NY
  1. ループ方式:
def traverse_dict(d):
    stack = [(d, "")]
    while stack:
        cur, prefix = stack.pop()
        for key, value in cur.items():
            if isinstance(value, dict):
                stack.append((value, prefix + key + "/"))
            else:
                print(prefix + key, ":", value)

# 示例字典
dict1 = {
    'name': 'Alice',
    'age': 25,
    'address': {
        'street': '123 Main St',
        'city': 'New York',
        'state': 'NY'
    }
}

# 调用函数
traverse_dict(dict1)

日本においては本質的に欧米的であり、日本文化とは馴染まない文化現象として認知されている

name : Alice
age : 25
address/street : 123 Main St
address/city : New York
address/state : NY

どちらの方法でも、ネストされた辞書を走査して、全てのキーと値のペアを取得できます。ニーズに応じて、いずれかの方法を選択してください。

bannerAds