0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

dictやlistの値を文字列で取り出す

Last updated at Posted at 2020-11-19

dict や list の値をa.bc.d.2.eのようなピリオド区切りの文字列を使って値を取り出したいことがあったので書いてみた。

def get_item(src, path):
    now = src
    for i in path.split('.'):
        if type(now) is list:
            now = now[int(i)]
        else:
            now = now[i]
    return now

nowは現在の値を入れるための変数。初期値は引数の dict or list。
pathをピリオドで分割してforで回す。
nowの値をforが終わるまで入れ替えていって最後にリターン。

ちなみに、Key名にピリオドが入っている場合は想定してないです。

my_dict = {
    'a': {
        'b': 'hello'
    },
    'c': {
         'd':[
             {'e': 3},
             {'e': 4},
             {'e': 5},
             {'e': 6},
         ]
     }
}

print(get_item(my_dict, 'a.b'))
print(get_item(my_dict, 'c.d.3.e'))
print(get_item(my_dict, 'c.d'))
# hello
# 6
# [{'e': 3}, {'e': 4}, {'e': 5}, {'e': 6}]
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?