1

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?

4
  • 3
    What have you tried yourself? You're grouping by some attribute of the list elements, do you need to use a list of dictionaries and a list of lists of dictionaries, or have you considered other data structures that would make this operation a lot easier like dataframes? Commented Oct 15, 2022 at 23:07
  • I tried something with loops but I don't like it. I haven't used any other data structures but anything that helps could be good Commented Oct 15, 2022 at 23:14
  • That first list of dictionaries looks like would make more sense as a dictionary itself... assuming the keys are guaranteed to be unique. Commented Oct 15, 2022 at 23:20
  • Do the keys represent anything besides the order in which those items were added to the original list? Is it possible to have holes or out-of-order keys, or is it always 1, 2, 3, 4...? If the former, you basically just have a list of dates, with additional nesting. Commented Oct 15, 2022 at 23:30

1 Answer 1

1
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.

Sign up to request clarification or add additional context in comments.

1 Comment

It is generous to give a UP-vote also. As it helps others to see it and also a reward to the author as compensation for energy and time. Yeah, sure, only if you think the answer is good. LoL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.