@MKsan (MK san)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

Pythonにおいて、辞書を用いた場合の平均気温の修正後の表示方法について

python初心者です。スッキリわかるPython入門を使った独学で勉強しています。
平均気温を求めるコードを使って勉強しており、for文で
辞書を用いた場合の平均気温の修正後の表示方法がわからないためご教授いただけると幸いです

作成したコード

#まず8時から17時までの気温を入力
temp = dict()
for num in range(10):
    kion = float(input(f'{num + 1}個目の気温を入力 >> '))
    temp[f'{num + 8}時の気温'] = kion
print(temp)

#13時の気温をN/Aに上書き。このとき新しい辞書temp_newを新規作成して、そこにtempを代入した後に13時台の気温をN/Aに上書きする
temp_new = dict(temp)
temp_new['13時の気温'] = 'N/A'

#新しい辞書temp_new_modifyを作成して、そこに13時の気温を除く
temp_new_modify = dict()
for num2 in range(len(temp_new)):
    if isinstance(temp_new[f'{num2 + 8}時の気温'], float):
        temp_new_modify[f'{num2 + 8}時の気温'] = ??? #右辺はどんな値を入れたらいいのでしょうか?
print(temp_new_modify)

実現したいこと

上記のコードの通り、temp_new_modifyに13時の気温を除いた辞書を作成したいと思います
print(temp_new_modify)の出力結果が

{'8時の気温': '入力値', '9時の気温': '入力値', '10時の気温': '入力値', '11時の気温': '入力値', '12時の気温': '入力値', '14時の気温': '入力値', '15時の気温': '入力値', '16時の気温': '入力値', '17時の気温': '入力値'}

となるようにしたいです。temp_new_modify[f'{num2 + 8}時の気温'] の右辺に入れるべき値を教えていただけると幸いです

0 likes

4Answer

temp_new_modify[f'{num2 + 8}時の気温'] = temp_new[f'{num2 + 8}時の気温']

前の連想配列の値を持ってくるだけでいいのでは?

1Like

Comments

  1. To display the corrected average temperature using a dictionary in Python, you can loop through the dictionary values, apply any correction needed, and then calculate the average

temp_new_modify[f'{num2 + 8}時の気温'] = temp_new[f'{num2 + 8}時の気温']
だとは思いますが、13時の気温を除くだけなら、その項目を削除するのが簡単だと思います。

#新しい辞書temp_newにtempを代入した後に`13時の気温`を削除する
temp_new = dict(temp)
del temp_new['13時の気温']
print(temp_new)

もしくは、

内包表記
#辞書tempから`13時の気温`を除いて、新しい辞書temp_newを作成する
temp_new = { x: temp[x] for x in temp if x != '13時の気温' }
print(temp_new)
0Like

Comments

  1. @MKsan

    Questioner

    amateさん

    コメントありがとうございます!
    たしかに
    temp_new_modify[f'{num2 + 8}時の気温'] = temp_new[f'{num2 + 8}時の気温']
    にしたほうがいですね・・・なぜ気づかなかったんだろう

    nak435さん
    コメントありがとうございます!
    del temp_new['13時の気温']したほうがシンプルなのは理解してましたが
    あえて私の知識習得のためにtemp_new_modifyの辞書を新たに作り知識を深めたいと思てました。またtemp_new_modifyを作らず、for文とif文を使った削除するやり方もあると学びました。勉強になりました

  2. 解決でよろしければ、当Q&Aをクローズしてください。

  3. @MKsan

    Questioner

    はい、解決したのでクローズとします

This answer has been deleted for violation of our Terms of Service.

This answer has been deleted for violation of our Terms of Service.

Your answer might help someone💌