LoginSignup
3

More than 3 years have passed since last update.

posted at

pythonの二次元辞書を宣言・初期化する

動作環境

Windows10
PyCharm
python3.7

やりたいこと

pythonの辞書型を二次元で初期化したい。

コード

def main():
    dic = {"a": 0, "b": 0, "c": 0}
    char_dic = {"a": 0, "b": 0, "c": 0}
    char_dic["a"] = dict(dic)
    char_dic["b"] = dict(dic)
    char_dic["c"] = dict(dic)

    # 任意の文字の次の文字の数を数える処理(二次元辞書が必要)
    string = "aacbbb"
    for i, n in enumerate(string):
        if i + 1 == len(string):
            break
        char_dic[string[i]][string[i + 1]] += 1

    for key, value in char_dic.items():
        for kk, vv in char_dic[key].items():
            print(str(key) + " ... " + str(kk) + " ... " + str(vv))


if __name__ == "__main__":
    main()

# 実行結果
a ... a ... 1
a ... b ... 0
a ... c ... 1
b ... a ... 0
b ... b ... 2
b ... c ... 0
c ... a ... 0
c ... b ... 1
c ... c ... 0

二次元辞書を0で初期化する

for文を使わない場合で、以下のように1つ1つ辞書のvalueを取得できます。
abcは、辞書のkeyです。二次元辞書を0で初期化していることを確認します。

    dic = {"a": 0, "b": 0, "c": 0}
    char_dic = {"a": 0, "b": 0, "c": 0}
    char_dic["a"] = dict(dic)
    char_dic["b"] = dict(dic)
    char_dic["c"] = dict(dic)

    print(char_dic["a"]["a"])
    print(char_dic["a"]["b"])
    print(char_dic["a"]["c"])
    print(char_dic["b"]["a"])
    print(char_dic["b"]["b"])
    print(char_dic["b"]["c"])
    print(char_dic["c"]["a"])
    print(char_dic["c"]["b"])
    print(char_dic["c"]["c"])

おまけ

pythonの二次元の辞書は、json形式で利用できます。
辞書のことを連想配列とかハッシュとかいいます。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
3