[英]How to convert this data structure in python
I have the following Python structure. 我有以下Python结构。
{'2015-03-03':
[{'traffic': 80.0, 'Server': 'Server1'},
{'traffic': 20.0, 'Server': 'Server2'}],
'2015-03-04':
[{'traffic': 100.0, 'Server': 'Server1'}]}
I need to convert this to a dictionary as 我需要将其转换为字典
{"Series":
[{'traffic': [80.0, 20.0], 'Server': 'Server1'},
{'traffic’: [100.0, 0], ’Server': 'Server2'}],
"dates" :
[“2015-03-03”, 2015-03-04”]}
I tried the following. 我尝试了以下方法。 (result had the first dictionary) (结果有第一本字典)
final_data = {}
final_data['series'] = []
final_data['dates'] = sorted(result.keys())
for key in final_data['dates']:
final_data['series'].append(result[key])
But this does not yield the converted data structure. 但这不会产生转换后的数据结构。 Any help? 有什么帮助吗?
What about: 关于什么:
di = {
'2015-03-03': [{'traffic': 80.0, 'Server': 'Server1'},
{'traffic': 20.0, 'Server': 'Server2'}],
'2015-03-04': [{'traffic': 100.0, 'Server': 'Server1'}]
}
dates = sorted(di.keys()) # Get all dates
servers = set(e['Server'] for v in di.values() for e in v) # Get all servers
# Refactor the dictionary
df = {}
for (k,v) in di.iteritems():
df[k] = {}
for elem in v:
df[k][elem['Server']] = elem['traffic']
# Compute series (if the [date][server] key-chain doesn't exist in df, use 0)
series = []
for server in servers:
traffic = []
for date in dates:
try: traffic.append(df[date][server])
except: traffic.append(0)
series.append({'traffic':traffic, 'Server':server})
# Create output dict
do = {
'Series': series,
'dates': dates,
}
print do
Output: 输出:
{
'Series': [
{'traffic': [80.0, 100.0], 'Server': 'Server1'},
{'traffic': [20.0, 0], 'Server': 'Server2'}
],
'dates': ['2015-03-03', '2015-03-04']
}
Note that this differs from your expected output . 请注意, 这与您的预期输出不同 。 In your expected output you had do['Series'][0]['traffic'] = [80.0, 20.0]
but I have [80.0, 100.0]
-- since they're the traffic entries corresponding to 'Server1'. 在您的预期输出中,您有do['Series'][0]['traffic'] = [80.0, 20.0]
但我有[80.0, 100.0]
-因为它们是与“ Server1”相对应的流量条目。
If you really want [80.0, 20.0]
, I'm going to need to know what logic you're using to make that connection. 如果您确实想要[80.0, 20.0]
,那么我将需要知道您用于建立该连接的逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.