LoginSignup
4
4

More than 5 years have passed since last update.

Pythonの辞書形式(dict)のforループ処理【key,value】

Posted at

辞書形式

以下のような辞書オブジェクトがあるとして

dict = {'key1': 1, 'key2': 2, 'key3': 3}

各要素のkey(キー)に対してforループ処理

素直にそのままfor文で回すとkeyが取得できる

for item in dict:  #もしくは for item in dict.key():
    print(item)
# key1
# key2
# key3

各要素のvalue(値)に対してforループ処理

values()というメソッドを使って取得

for item in dict.values():
    print(item)
# 1
# 2
# 3

keyに対するvalueを取得するには

print(dict['key1'])  #辞書オブジェクト['key']
# 1

辞書に要素を追加・更新

これがやりたかったこと。
(DBから辞書形式で取得して、その辞書のあるkeyのvalueをエンコードしたものを追加したかった)

ということで、以下のようにすると辞書に要素を追加・更新できる

要素の追加

dict['key4'] = 4
print(dict)
# {'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4}

要素の更新

dict['key1'] = 100
print(dict)
# {'key1': 100, 'key2': 2, 'key3': 3}

DBから辞書形式で取得したデータをもとにした場合

DBで辞書形式で取得するとこんな感じで取得できる
・keyに値するのがカラム名
・valueに値するのがカラム内のデータ

data_list = [{'name': '東京ディズニーランド', 'country': '日本'}, {'name': 'ウォルト・ディズニー・ワールド・リゾート', 'country': 'アメリカ'}, {'name': 'ディズニーランド・パリ', 'country': 'イタリア'}]

for item in data_list:
    print(item['name'])
# 東京ディズニーランド
# ウォルト・ディズニー・ワールド・リゾート
# ディズニーランド・パリ

エンコードした名称を追加してみる

"name"カラムのデータをエンコードして追加

import urllib.parse

for item in data_list:
    encode_name = urllib.parse.quote(item['name'])
    item['encode_name'] = encode_name
    print(item)
# {'name': '東京ディズニーランド', 'country': '日本', 'encode_name': '%E6%9D%B1%E4%BA%AC%E3%83%87%E3%82%A3%E3%82%BA%E3%83%8B%E3%83%BC%E3%83%A9%E3%83%B3%E3%83%89'}
# {'name': 'ウォルト・ディズニー・ワールド・リゾート', 'country': 'アメリカ', 'encode_name': '%E3%82%A6%E3%82%A9%E3%83%AB%E3%83%88%E3%83%BB%E3%83%87%E3%82%A3%E3%82%BA%E3%83%8B%E3%83%BC%E3%83%BB%E3%83%AF%E3%83%BC%E3%83%AB%E3%83%89%E3%83%BB%E3%83%AA%E3%82%BE%E3%83%BC%E3%83%88'}
# {'name': 'ディズニーランド・パリ', 'country': 'イタリア', 'encode_name': '%E3%83%87%E3%82%A3%E3%82%BA%E3%83%8B%E3%83%BC%E3%83%A9%E3%83%B3%E3%83%89%E3%83%BB%E3%83%91%E3%83%AA'}
4
4
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
4