これについて質問がありますが、見つけられません。多次元辞書をループして計算する
私はこのような辞書があります:私は辞書をループにしたいし、可能な場合は辞書を変更すること、累積ポイントを計算
data = {
"Jan": {
"2017-01-01 00:00:00": {
"001": 10,
"002": 20,
"003": 30
},
"2017-01-01 01:00:00": {
"001": 20,
"002": 40,
"003": 50
},
"2017-01-01 02:00:00": {
"001": 90,
"002": 50,
"003": 60
}
}
}
を。例えば、001
のためにそれは私が最終的な累積和を取得する必要はありません
data["Jan"]["2017-01-01 00:00:00"]["001"] == 10
data["Jan"]["2017-01-01 01:00:00"]["001"] == 30
data["Jan"]["2017-01-01 02:00:00"]["001"] == 120
だろう、私は相対したいです。
今、私はこのコードを持っている:
import copy
from datetime import datetime, timedelta
copydata = copy.deepcopy(data)
# I made a copy because I have an if statement and Python was
complaining that the dictionary changed size during iteration
for i, month in enumerate(copydata):
for dt in copydata[month]:
for user in copydata[month][dt]:
current_datetime = datetime.strptime(dt, '%Y-%m-%d %H:00:00')
cumulativepoints=data[month][dt][user] # getting the current hour's points. Since the loop is in random order, it can start at any time
if current_datetime.hour > 0: # if the hour is 0 then it's the first hour and I don't need to calculate anything
for x in range(1, current_datetime.hour+1): # starting at 01:00:00 till the current_datetime.hour plus one to count itself
past_time = current_datetime - timedelta(hours=x)
past_time = past_time.strftime('%Y-%m-%d %H:00:00')
if data[month][past_time]:
cumulativepoints += data[month][past_time][user]
data[month][past_time][user] = cumulativepoints # <--- the error happens here
をしかし、その行data[month][past_time][user] = cumulativepoints
で、Pythonはエラーがスローされます。TypeError: list indices must be integers, not str
私はこのコードはそれがあるべきよりも多く複雑であるかなり確信しています。しかし、それは多くのエラーメッセージのために多くの適応が行われた結果です。
'dict'は良いことするつもりはありませんこのためのデータ構造は、順序付けられておらず、あなたはランダムな順序でキーを反復しようとしています。しかし、あなたが達成しようとしているもののために命令は重要です。 –
@rlcabral、私はPython 2.7.3でどんな種類のエラーも受け取りません。問題があると仮定して、変数 'cumulativepoints'を' int() '関数にカプセル化してみてください。同様に 'data [month] [past_time] [user]'と同じ行にしてください。私はあなたが間違って整数の代わりに文字列を渡しているという気持ちを得ています。 – SirJames
@SirJames、同じエラー – rlcabral