Home > OS >  How to merge items from a key in dict to a list in Python? (see example)
How to merge items from a key in dict to a list in Python? (see example)

Time:02-21

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:

  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.

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']}]
  • Related