LoginSignup
0
0

More than 1 year has passed since last update.

Pythonでjavascriptのように辞書の分割代入をしたい

Last updated at Posted at 2022-04-06

便利なjavascriptのオブジェクトの分割代入。

便利ですよねぇ

destructuring.js
const data = {
  limit: 100,
  offset: 50,
  key1: 0,
  key2: 'string',
}

const { limit, offset, ...other } = data

console.log(limit)   // 100
console.log(offset)  // 50
console.log(other)   // { key1: 0, key2: 'string' }

Pythonの辞書でも同じようなことをしたい。

あまり綺麗ではないが、一応できた

destructuring.py
data = {
    'limit': 100,
    'offset': 50,
    'key1': 0,
    'key2': 'string',
}

limit, offset, other = (lambda limit, offset, **other: (limit, offset, other))(**data)

print(limit)   # 100
print(offset)  # 50
print(other)   # {'key1': 0, 'key2': 'string'}

lambdaを使わないならまだ綺麗だが、汎用性に欠ける

destructuring_func.py
def destructuring(limit, offset, **other):
    return limit, offset, other


data = {
    'limit': 100,
    'offset': 50,
    'key1': 0,
    'key2': 'string',
}

limit, offset, other = destructuring(**data)

print(limit)   # 100
print(offset)  # 50
print(other)   # {'key1': 0, 'key2': 'sting'}

良い書き方はないものか

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