0

I have a dict and its keys are dates, its items are some numbers and sum of the numbers with Total as shown below. I want to group the keys by year with their sum of Total value. I know how to do it if I use fixed dict. But I will always write different changeable dates. My example list is;

{
        "15-12-2017" : {
          "1" : "abc",
          "2" : "def",
          "Total" : "2"
        },
        "16-12-2017" : {
          "1" : "ghi",
          "2" : "jkl",
          "3" : "mno",
          "Total" : "3"
        }
        "17-12-2017" : {
          "1" : "ghi",
          "2" : "jkl",
          "3" : "mno",
          "4" : "pqr",
          "Total" : "4"
        }
        "15-12-2018" : {
          "1" : "ghi",
          "2" : "jkl",
          "3" : "mno",
          "Total" : "3"
        }
        "16-12-2018" : {
          "1" : "ghi",
          "2" : "jkl",
          "Total" : "2"
        }
        "18-12-2019" : {
          "1" : "ghi",
          "2" : "jkl",
          "3" : "mno",
          "Total" : "3"
        }
}

I want to get a new list like;

{"2017":9,"2018":5,"2019":3}

I can do only;

for key in my_list:
    if key.split('-')[2] == '2017':
        l_2017.append(key)

But as I said before, I will insert many changeable dates. How can I cluster them like this format?

1 Answer 1

3

Here is one way to do it:

from dateutil.parser import parse

date_data = {
    "15-12-2017" : {
        "1" : "abc",
        "2" : "def",
        "Total" : "2"
    },
    "16-12-2017" : {
        "1" : "ghi",
        "2" : "jkl",
        "3" : "mno",
        "Total" : "3"
    },
    "17-12-2017" : {
        "1" : "ghi",
        "2" : "jkl",
        "3" : "mno",
        "4" : "pqr",
        "Total" : "4"
    },
    "15-12-2018" : {
        "1" : "ghi",
        "2" : "jkl",
        "3" : "mno",
        "Total" : "3"
    },
    "16-12-2018" : {
        "1" : "ghi",
        "2" : "jkl",
        "Total" : "2"
    },
    "18-12-2019" : {
        "1" : "ghi",
        "2" : "jkl",
        "3" : "mno",
        "Total" : "3"
    }
}

sums = {}

for date, data in date_data.items():
    year = str(parse(date).year)
    total = int(data['Total'])
    # Update sum if already tracking, otherwise create new entry in dictionary
    sums[year] = sums[year] + total if year in sums else total

print(sums)

This gives the output:

{'2017': 9, '2018': 5, '2019': 3}
Sign up to request clarification or add additional context in comments.

Comments

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.