LoginSignup
0
0

More than 3 years have passed since last update.

辞書をkeyとvalueのリストに分解する

Last updated at Posted at 2019-06-09

タイトルそのまま。

普通にやるならこう。

>>> D = {"a":1,"b":2,"c":3}
>>> D
{'a': 1, 'b': 2, 'c': 3}

>>> [*D.keys()] #[*D]でも可
['a', 'b', 'c']
>>> [*D.values()] 
[1, 2, 3]

癖の強い書き方

>>> key,value = [*zip(*D.items())]
>>> key
('a', 'b', 'c')
>>> value
(1, 2, 3)

リストじゃないじゃん。
(以下はshiracamusさんにご指摘いただき簡潔に修正致しました。)

>>> key,value = map(list,zip(*D.items()))
>>> key
['a', 'b', 'c']
>>> value
[1, 2, 3]

他人に見せないコードならなんでも1行でやっちゃいたい人。

以上。

追記。

shiracamusさんにコメントで以下のような書き方も教えていただきました。

>>> (*key,),(*value,)=zip(*D.items())
>>> key
['a', 'b', 'c']
>>> value
[1, 2, 3]

なぜこう書けるのかはコメント欄にて。

0
0
5

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