Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
     {
         "page": "NEWS",
         "position": ["SECOND_ITEM"]
     },
     {
        "page": "GLOBAL",
        "position": ["BOTTOM-RIGHT", "TOP-RIGHT"]
    }
 ]

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading