0
0

Pythonにおける多次元辞書のキーと値の同時生成方法およびキーの存在確認方法

Posted at

きっかけ

Pythonの多次元辞書に関する情報があまり見つからず,何か一発でキーと値を生成できたり,キーの存在確認できたりできないものかと考えて適当にコード書いたものです。
再帰を使っているのでメモリにあまり優しくない方法ですけど、参考になれば幸いです。
何かバグ等ありましたらお教えいただけますと大変勉強になります。

多次元辞書のキーと値の同時生成方法

コードと実行例

code
def createMulDimDict(dic, keys, val):
    dic.setdefault(keys[0], {})
    if len(keys) == 1:
        dic[keys[0]] = val
    else:
        createMulDimDict(dic[keys[0]], keys[1:], val)
        
dic = {}
createMulDimDict(dic, ['food', 'meat'] , 'beaf')
print(dic)
# {'food': {'meat': 'beaf'}}

createMulDimDict(dic, ['food', 'fruit'] , ['apple', 'banana'])
print(dic)
# {'food': {'meat': 'beaf', 'fruit': ['apple', 'banana']}}

createMulDimDict(dic, ['machine', 'vehicle'], {'car' : ['bus', 'truck'], 'others' : ['ship', 'plane', 'helicopter']})
print(dic)
# {'food': {'meat': 'beaf', 'fruit': ['apple', 'banana']}, 'machine': {'vehicle': {'car': ['bus', 'truck'], 'others': ['ship', 'plane', 'helicopter']}}}

# JSON形式に変換
import json
json_name = 'example.json'
with open(json_name, 'w') as fp:
    json.dump(dic, fp, indent=4)
example.json
{
    "food": {
        "meat": "beaf",
        "fruit": [
            "apple",
            "banana"
        ]
    },
    "machine": {
        'vehicle': {
            'car': ['bus', 'truck'],
            'others': ['ship', 'plane', 'helicopter']
        }
    }
}

実装のポイントは多次元キーを文字列のリストとして引数にするところ。
これのおかげで、再帰でキーをスライスして渡しても文字列として渡せる感じです。
値には、辞書の値として受け入れられるものならば,文字列でもリストでも辞書でも入れられます。
多次元辞書が「辞書→リスト→辞書」のように途中にリストを挟む場合などもこれをベースに少しいじれば実装できます。

多次元辞書のキーの存在確認方法

コードと実行例

def existKeys(dic, keys)
    if len(keys) == 1:
        return keys[0] in dic
    elif keys[0] in dic:
        return existKey(dic[keys[0], keys[1:)
    else:
        return False

with open('example.json', 'r') as fp:
    example = json.load(fp)

print(existKeys(example, ['machine', 'vehicle', 'others']))
# True

print(existKeys(example, ['food', 'vehicle']))
# False

こちらもポイントは上と同じく引数の文字列リストです。
['A', 'B', 'C']なんていうキーの存在確認をする際に'B'の時点でキーがなかった場合を想定して,elif節の条件を書いてます。

0
0
0

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
  3. You can use dark theme
What you can do with signing up
0
0