Having this response from Facebook Graph API:
"data": [
{
"name": "page_impressions",
"period": "day",
"values": [
{
"value": 0,
"end_time": "2019-04-16T07:00:00+0000"
},
{
"value": 0,
"end_time": "2019-04-17T07:00:00+0000"
}
],
"title": "Daily Total Impressions",
"description": "Daily: The number of times any content from your Page or about your Page entered a person's screen. This includes posts, check-ins, ads, social information from people who interact with your Page and more. (Total Count)",
},
{
"name": "page_fan_adds",
"period": "day",
"values": [
{
"value": 0,
"end_time": "2019-04-16T07:00:00+0000"
},
{
"value": 0,
"end_time": "2019-04-17T07:00:00+0000"
}
],
"title": "Daily New Likes",
"description": "Daily: The number of new people who have liked your Page (Total Count)",
"id": "145648302731807/insights/page_fan_adds/day",
}]}
My code until now:
def manipulate(result):
dates = []
if "data" in result:
dates = result['data']
entriesToRemove = {'description', 'title', 'period', 'id'}
for element in dates:
for entries in entriesToRemove:
element.pop(entries, False)
return dates
…which returns:
[{'values': [{'end_time': '2019-04-14T07:00:00+0000', 'value': 0}, {'end_time': '2019-04-15T07:00:00+0000', 'value': 0}], 'name': 'page_impressions'}, {'values': [{'end_time': '2019-04-16T07:00:00+0000', 'value': 0}, {'end_time': '2019-04-17T07:00:00+0000', 'value': 0}], 'name': 'page_fan_adds'}]
… I would like to manipulate it to this final form:
[{
"page_impressions": 0,
"end_time": "2019-04-16T07:00:00+0000",
},
{
"page_impressions": 0,
"end_time": "2019-04-17T07:00:00+0000",
},
{
"page_fan_adds": 0,
"end_time": "2019-04-16T07:00:00+0000",
},
{
"page_fan_adds": 0,
"end_time": "2019-04-17T07:00:00+0000",
},
]
How should I approach this situation? I can’t figure it out about manipulating the response. Or maybe there is another way to do this…
2
Answers
Assuming your
dict
is namedd
:Note that this solution will not do the operations in place. Instead it will take the needed elements and create a new object. The speed is
O(n)
, and it is fairly readable.Output: