その('Time ': '2017-12-01T13:54:04', 'Energy [kWh]': '0.01')
構文は有効ではありませんPython。実際に辞書のリストが必要だと仮定すると、その変換を実行するのは難しくありません。
タイムスタンプを取得して、他の各アイテムと組み合わせることができるようにしてから、残りのアイテムを新しい構造に簡単にコピーできるようにすることができます。これは、関数に渡された元のdictを変更することに注意してください。それが必要でない場合は、渡されたdictのコピーを作成するか、if
テストをループに入れて、新しい項目にデータをコピーして、時間項目をスキップします。
def convert(old):
time_key = 'Time '
# Save the time
time_item = (time_key, old[time_key])
# Add remove it
del old[time_key]
# Copy remaining items to new dicts and save them in a list
return [dict([time_item, item]) for item in old.items()]
row = {
'Time ': '2017-12-01T13:54:04',
'Energy [kWh]': '0.01',
'Voltage [V]': '221.64',
'Current [A]': '0.08',
}
new_data = convert(row)
for d in new_data:
print(d)
出力
{'Time ': '2017-12-01T13:54:04', 'Energy [kWh]': '0.01'}
{'Time ': '2017-12-01T13:54:04', 'Voltage [V]': '221.64'}
{'Time ': '2017-12-01T13:54:04', 'Current [A]': '0.08'}
は、ここでは、オリジナルの辞書を変異またはコピーしたくない場合は、それを行う方法は次のとおりです。
def convert(old):
time_key = 'Time '
# Save the time
time_item = (time_key, old[time_key])
# Copy other items to new dicts and save them in a list
return [dict([time_item, (key, val)])
for key, val in old.items() if key != time_key]
注これがあることタイムキーではないことを確認するためにすべてのキーをテストする必要があるため、効率が低下します。
OrderedDict
秒のリストにデータを保存するには、我々は少しロジックを変更する必要があります。また、項目が希望の順序になるようにOrderedDict
を適切に作成する必要があります。
from collections import OrderedDict
from pprint import pprint
def convert(row):
time_key = 'Time '
time_value = row[time_key]
new_data = []
for key, val in row.items():
if key == time_key:
continue
new_data.append(OrderedDict(Device=key, Measure=val, Time=time_value))
return new_data
row = {
'Time ': '2017-12-01T13:54:04', 'Energy [kWh]': '0.01',
'Voltage [V]': '221.64', 'Current [A]': '0.08'
}
new_data = convert(row)
pprint(new_data)
出力
[OrderedDict([('Device', 'Energy [kWh]'),
('Measure', '0.01'),
('Time', '2017-12-01T13:54:04')]),
OrderedDict([('Device', 'Voltage [V]'),
('Measure', '221.64'),
('Time', '2017-12-01T13:54:04')]),
OrderedDict([('Device', 'Current [A]'),
('Measure', '0.08'),
('Time', '2017-12-01T13:54:04')])]
あなたは最後の行にタイプミスがあります: '' 'TIMEVALUE – Val
@val thas対Timetvalue'は、変数の名前を変更のタイプミスでした。 – AhmyOhlin
確かに、TimeValueは範囲内にありません – Val