4
1

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】dictのkeyを日本語にするとKeyErrorになる

Posted at

はじめに

pythonのdictでkeyを日本語に設定すると、keyerrorに直面しました。
見た目は同じなのに、KeyErrorですと言われたときの解決方法です。

半ば強引ですがとりあえずこれでなんとかなります。

解決策

import unicodedata
KeyMatched_str = unicodedata.normalize('NKFC', KeyError_str)

原因

dictKeyErrorになる原因は、日本語の濁点や半濁点にありました。
どういうことかというと、utf-8では「ど」などの濁点・半濁点のつく文字には以下の二通りの表現方法があるためです。

  • 単純に「ど」
  • 「と」+「濁点」

パソコンで表示される上では、上の2つは全く同じ文字ですがutf-8などで表示すると違うことがわかります。
試しに以下のコードを実行してみます。

print(b'\xe3\x81\xa9'.decode('utf-8'))
print(b'\xe3\x81\xa8\xe3\x82\x99'.decode('utf-8'))
print(b'\xe3\x81\xa8'.decode('utf-8'))

--result--
ど
ど
と

このように、違うことがわかります。
Pythondictはこの違いも判別しているらしく、KeyErrorが発生してしまうことがあるようです。

参考

ほぼ参考サイトのコピペです。。。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?