Split Python Array based on a property

Question:

I have a Python List like this:

myList = [
    {
        "key": 1,
        "date": "2020-01-02"
    },
    {
        "key": 2,
        "date": "2020-02-02"
    },
    {
        "key": 3,
        "date": "2020-01-03"
    },
    {
        "key": 4,
        "date": "2020-01-02"
    },
    {
        "key": 5,
        "date": "2020-02-02"
    },
]

Now I want to split the array based on the property "date". I want my list to look like this

myList = [
    [
        {
            "key": 1,
            "date": "2020-01-02"
        },
        {
            "key": 4,
            "date": "2020-01-02"
        },
    ],
    [
        {
            "key": 2,
            "date": "2020-02-02"
        },
        {
            "key": 5,
            "date": "2020-02-02"
        },
    ],
    [
        {
            "key": 3,
            "date": "2020-01-03"
        },
    ]
]

So I want a new array for each specific date in the current list. Can someone help me to achieve that?

Asked By: Korab Duklini

||

Answers:

d={}
for i in range(len(myList)):
    d.setdefault(myList[i]['date'], []).append(i) 
myList = [ [myList[i] for i in v] for k,v in d.items() ]  # replace the original `myList` following PO behavior.

Logic:

You want to group the data based on ‘date’ that means you need a dictionary data structure. The rest are just implementation details.

Answered By: Xin Cheng
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.