Home > other >  Split Python Array based on a property
Split Python Array based on a property

Time:10-16

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? Thanks

CodePudding user response:

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.

CodePudding user response:

List = [
{
    "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"
}]


newList = []
while List:
     d1=List.pop()
     newList.append([d1])
 
     for i in reversed(range(len(List))):
          d2=List[i]
          if d1["date"]==d2["date"]:
           
               newList[-1].append(d2)
               List.pop(i)
           
 
print(newList)
  • Related