0
0

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 1 year has passed since last update.

Rubyのdigをpythonでやる

Last updated at Posted at 2023-02-15

課題

ネストされたdictから特定の値を取り出したいとき

Rubyの場合

以下のように、nullチェックをしながらいい感じに取り出してくれる

data_a = { 'name': { 'first_name': 'yamada', 'last_name': 'taro' } }
data_b = { 'name': { 'last_name': 'taro' } }

p data.dig('name', 'first_name')
# => yamada

p data.dig('name', 'first_name')
# => nil

Pythonの場合

digのようなメソッドはないので愚直にやると以下のような方法になる。

data_a = { 'name': { 'first_name': 'yamada', 'last_name': 'taro' } }
data_b = { 'name': { 'last_name': 'taro' } }

if 'name' in data_a and 'first_name' in data_a['name']:
    print(data_a['name']['first_name'])
else
    print(None)
# => yamada

if 'name' in data_b and 'first_name' in data_b['name']:
    print(data_b['name']['first_name'])
else
    print(None)
# => None

get()演算子を使うとスマートになる。

print(data_a.get("name", {}).get("first_name", None))
# => yamada

print(data_b.get("name", {}).get("first_name", None))
# => None

python3.10以降では>|演算子を使った書き方もできるらしいが、個人的にはスマートには見えなかったので割愛

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?