我有这样的数据:
data = {
'impressions': {'20190513': '50922', '20190514': '62343', '20190515': '34866'},
'clicks': {'20190513': '25', '20190514': '28', '20190515': '12'}}
但困惑于更改结构:
[{
'date': '20190513',
'impressions': '50922',
'clicks': '25',
},
{
'date': '20190514',
'impressions': '62343',
'clicks': '28',
},
{
'date': '20190515',
'impressions': '34866',
'clicks': '12',
}]
我尝试了几次,但是失败了。请帮帮我。谢谢...
答案 0 :(得分:3)
使用列表和字典理解。适用于Python 2和3:
public <T> T readValue(String content, Class<T> valueType)
throws IOException, JsonParseException, JsonMappingException
{
return (T) _readMapAndClose(_jsonFactory.createParser(content), _typeFactory.constructType(valueType));
}
输出:
from pprint import pprint
d = [{'date': date, 'impressions': data['impressions'][date], 'clicks': data['clicks'][date]} for date in data['clicks']]
pprint(d)
答案 1 :(得分:2)
尝试一下:
data = {
'impressions': {'20190513': '50922', '20190514': '62343', '20190515': '34866'},
'clicks': {'20190513': '25', '20190514': '28', '20190515': '12'}}
impressions = data['impressions']
clicks = data['clicks']
list1 = []
for key,value in impressions.items():
dict1 = {}
dict1['date'] = key
dict1['impressions'] = value
if key in clicks:
dict1['clicks'] = clicks[key]
list1.append(dict1)
print(list1)
O / P:
[{'date': '20190513', 'impressions': '50922', 'clicks': '25'}, {'date': '20190514', 'impressions': '62343', 'clicks': '28'}, {'date': '20190515', 'impressions': '34866', 'clicks': '12'}]
答案 2 :(得分:1)
尝试一下:
data = {
'impressions': {'20190513': '50922', '20190514': '62343', '20190515': '34866'},
'clicks': {'20190513': '25', '20190514': '28', '20190515': '12'}}
result = []
for i in data['impressions'].keys():
result.append({'date': i, 'impressions': data['impressions'][i], 'clicks': data['clicks'][i]})
print(result)
这是我的结果:
[{'date': '20190513', 'impressions': '50922', 'clicks': '25'}, {'date': '20190514', 'impressions': '62343', 'clicks': '28'}, {'date': '20190515', 'impressions': '34866', 'clicks': '12'}]
答案 3 :(得分:1)
尝试一下:
data = {
'impressions': {'20190513': '50922', '20190514': '62343', '20190515': '34866'},
'clicks': {'20190513': '25', '20190514': '28', '20190515': '12'}}
result = [{"date":key,"impressions":value,"clicks":data["clicks"][key]} for key,value in data["impressions"].items()]
print(result)