0
2

More than 1 year has passed since last update.

辞書型(dict)の値(value)に数字を足す

Last updated at Posted at 2022-09-14

Googleで調べた際に、値に数字を足す関数がPythonでは見つからなかったので、自作しました。
計算コストを考慮してないコードのため、もっといい方法があれば教えていただけると幸いです。

最後に自身がしたかったことを載せます。

【解決法】

=の前に+をつければいいだけです。Pythonの四則演算ができる方であれば、簡単ですね。
dict[key] *= number

例:

test_dict = {}
test_dict["math"] = 90
test_dict["science"] = 10

'''
数学に10を追加、化学に20を追加
'''
test_dict["math"] += 10
test_dict["science"] += 20

[実装したかった事]

For文を回して、同じキー(Key)の場所には数字を足し、該当するKeyがない場合には新しいキー(Key)を作成して値(value)を与えることがしかったです。

例:

test_dict = {}
count = 10
for k in [1, 2, 3, 4, 5]:
    test_dict[k] = count
    count -= 1

for k in [1,4, 5, 6, 1]
    try:
        test_dict[k] *= count
        count -= 1
    except:
        test_dict[k] +- count
        count -= 1
0
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
0
2