如何在python中转换这个数据结构

时间:2015-03-12 05:33:59

标签: python

我有以下Python结构。

{'2015-03-03': 
    [{'traffic': 80.0, 'Server': 'Server1'},
     {'traffic': 20.0, 'Server': 'Server2'}],
 '2015-03-04':
    [{'traffic': 100.0, 'Server': 'Server1'}]}

我需要将其转换为字典

{"Series": 
    [{'traffic': [80.0, 20.0], 'Server': 'Server1'},
     {'traffic’: [100.0, 0], ’Server': 'Server2'}],
 "dates" : 
    [“2015-03-03”, 2015-03-04”]}

我尝试了以下内容。 (结果有第一本字典)

final_data = {}
final_data['series'] = []
final_data['dates'] = sorted(result.keys())
for key in final_data['dates']:
    final_data['series'].append(result[key])

但是这不会产生转换后的数据结构。有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

怎么样:

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

输出:

{
    'Series': [
        {'traffic': [80.0, 100.0], 'Server': 'Server1'}, 
        {'traffic': [20.0, 0], 'Server': 'Server2'}
    ], 
    'dates': ['2015-03-03', '2015-03-04']
}

请注意,这与您预期的输出不同。在您的预期输出中,您有do['Series'][0]['traffic'] = [80.0, 20.0],但我有[80.0, 100.0] - 因为它们是与'Server1'对应的流量条目。

如果你真的想要[80.0, 20.0],我将需要知道你用来建立连接的逻辑。