-1

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"]
    }
 ]
Alleh parast
  • 63
  • 1
  • 6
  • 1
    "I can't think of a way to do the thing below" Well, what do you imagine are the logical steps to solving the problem? If you have two dictionaries in separate variables, with the same `"page"` key and different `"position"` keys, could you write code that gives you the merged result? (Hint: what should the "page" value be in the result? How do you get the "position" value?) What if you had one dictionary and a list of other dictionaries - could you find the one with the appropriate `"page"` (if any) and do the merge? What if there weren't anything to merge with - what would make sense to do? – Karl Knechtel Feb 20 '22 at 16:32
  • Does https://stackoverflow.com/questions/26910708/merging-dictionary-value-lists-in-python help understand how to do the merging? Can you figure out which dictionaries to merge? – Karl Knechtel Feb 20 '22 at 16:48

2 Answers2

1

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:

  1. So you can first iterate over the lst and get the page and position of every dictionary inside lst.
  2. Then you check to see if there is already a dictionary with the same page in the res list.
  3. If there is, you append the position to it. Otherwsie (the else part of the for-loop is executed) you append a new dictionary to the res list with {'page': page, 'position': [position]} format. The position is now ready to be appended next time.
S.B
  • 13,077
  • 10
  • 22
  • 49
1

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']}]
PandasasPD
  • 115
  • 1
  • 4
  • 1
    Probably easier to keep as a DataFrame and get the records instead of post processing the results: `result_list = df.groupby('page',as_index=False).agg(list).to_dict(orient='records')` – Henry Ecker Feb 20 '22 at 17:11
  • @HenryEcker: Couldn't agree more with your solution. Perfecto! – PandasasPD Feb 20 '22 at 17:18