I can't think of a way to do the thing below
How can I turn this dictionary
[
{
"page": "NEWS",
"position": "SECOND_ITEM"
},
{
"page": "GLOBAL",
"position": "BOTTOM-RIGHT"
},
{
"page": "GLOBAL",
"position": "TOP-RIGHT"
}
]
to this dictionary in python
[
{
"page": "NEWS",
"position": ["SECOND_ITEM"]
},
{
"page": "GLOBAL",
"position": ["BOTTOM-RIGHT", "TOP-RIGHT"]
}
]
CodePudding user response:
Try this:
lst = [
{
"page": "NEWS",
"position": "SECOND_ITEM"
},
{
"page": "GLOBAL",
"position": "BOTTOM-RIGHT"
},
{
"page": "GLOBAL",
"position": "TOP-RIGHT"
}
]
res = []
for dictionary in lst:
page, position = dictionary['page'], dictionary['position']
for d in res:
if d['page'] == page:
d['position'].append(position)
break
else:
res.append({'page': page, 'position': [position]})
print(res)
output:
[{'page': 'NEWS', 'position': ['SECOND_ITEM']}, {'page': 'GLOBAL', 'position': ['BOTTOM-RIGHT', 'TOP-RIGHT']}]
Explanation:
- So you can first iterate over the
lst
and get thepage
andposition
of every dictionary insidelst
. - Then you check to see if there is already a dictionary with the same
page
in theres
list. - If there is, you append the
position
to it. Otherwsie (theelse
part of the for-loop is executed) you append a new dictionary to theres
list with{'page': page, 'position': [position]}
format. Theposition
is now ready to be appended next time.
CodePudding user response:
One more solution could be this:
data = [
{
"page": "NEWS",
"position": "SECOND_ITEM"
},
{
"page": "GLOBAL",
"position": "BOTTOM-RIGHT"
},
{
"page": "GLOBAL",
"position": "TOP-RIGHT"
}
]
df = pd.DataFrame(data)
result = df.groupby('page')['position'].apply(list).to_dict()
result_list = []
for key, value in result.items():
result_dict = {}
result_dict['page']= key
result_dict['position'] = value
result_list.append(result_dict)
result_list
Here is the output:
[{'page': 'GLOBAL', 'position': ['BOTTOM-RIGHT', 'TOP-RIGHT']},
{'page': 'NEWS', 'position': ['SECOND_ITEM']}]