3
2

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 5 years have passed since last update.

Pythonでの辞書の分割代入

Posted at

JavaScriptオブジェクトの分割代入 便利ですよね。

JavaScript
const obj = { b: 14, a: 12 }
const { a, b, c } = obj
console.log(a, b, c) // 12 14 undefined

Pythonでの辞書の分割代入の例

Python
dct = { "b": 14, "a": 12 }
a, b, c = (dct.get(k) for k in ("a", "b", "c"))
print("%s %s %s" % (a, b, c)) # 12 14 None
Python
dct = { "b": 14, "a": 12 }
a, b, c = (lambda a=None, b=None, c=None: locals().values())(**dct)
print("%s %s %s" % (a, b, c)) # 12 14 None

複雑な代入を行う場合はどのようにするのが適切なのでしょうかね…?

他の言語の例

Ruby
hash = { b: 14, a: 12 }
a, b, c = hash.values_at :a, :b, :c
p a, b, c
=begin
12
14
nil
=end
PHP
<?php

$assoc = ["b" => 14, "a" => 12];
list("a" => $a, "b" => $b, "c" => $c) = $assoc;
var_dump($a, $b, $c);
/*
int(12)
int(14)
NULL
*/
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?