4
3

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.

辞書のkeyとvalueを1行で入れ替える

Last updated at Posted at 2019-06-17

内包表記でできるじゃん。

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

>>> {value:key for key,value in D.items()}
{1: 'a', 2: 'b', 3: 'c'}

でも個人的には以下でやっちゃうのが好き

>>> dict(map(reversed,D.items()))
{1: 'a', 2: 'b', 3: 'c'}

#lambdaでもできる
>>> dict(map(lambda x:x[::-1] ,D.items()))
{1: 'a', 2: 'b', 3: 'c'}

valueが被ってた場合は、どちらかで上書きされる。
(辞書は順番が保証されないため一概にどちらとは言えない)

>>> DW
{'a': 1, 'b': 2, 'c': 3, 'd': 2}

>>> {value:key for key,value in DW.items()}
{1: 'a', 2: 'd', 3: 'c'}
>>> dict(map(reversed,DW.items()))
{1: 'a', 2: 'd', 3: 'c'}

もちろん元のvalueが辞書のkeyにできる値であることが条件。
(リストとかは辞書のkeyにできないので)
内包表記が好きじゃないならこういった書き方もできるなって話。

以上。

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?