Home > Software engineering >  For loop to concatenate JSON object if one of the attributes is the same
For loop to concatenate JSON object if one of the attributes is the same

Time:08-05

Python noob so bear with me please. I have this set of data:

[
   {
      "Created": "2022-07-04 13:27:35 UTC",
      "Text": "Text"
    },
    {
      "Created": "2022-07-04 13:37:35 UTC",
      "Text": "Random"
    },
    {
      "Created": "2022-07-04 13:40:35 UTC",
      "Text": "People"
    },
    {
      "Created": "2022-08-06 13:27:35 UTC",
      "Text": "Test"
    },
    {
      "Created": "2022-09-04 23:29:05 UTC",
      "Text": "Test"
    },

]

In my code I'm looping over them and creating a separate array of objects but with human readable time string. Since there are multiple created at that are the same time, is there way I can concatenate them into one object while looping? like so

[
   {
      "Created": "July 4th 2022",
      "Text": "Text Random People"
    },
    {
      "Created": "August 8th 2022",
      "Text": "Test"
    },
    {
      "Created": "September 4th 2022",
      "Text": "Test"
    },

]

CodePudding user response:

To pretty format the date you first need to parse it with datetime.strptime and then format it with datetime.strftime. Rest of the script is standard grouping by this string:

from datetime import datetime

data = [
    {"Created": "2022-07-04 13:27:35 UTC", "Text": "Text"},
    {"Created": "2022-07-04 13:37:35 UTC", "Text": "Random"},
    {"Created": "2022-07-04 13:40:35 UTC", "Text": "People"},
    {"Created": "2022-08-06 13:27:35 UTC", "Text": "Test"},
    {"Created": "2022-09-04 23:29:05 UTC", "Text": "Test"},
]

# https://stackoverflow.com/a/16671271/10035985
def ord(n):
    return str(n)   (
        "th"
        if 4 <= n % 100 <= 20
        else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")
    )


out = {}
for d in data:
    dt = datetime.strptime(d["Created"], "%Y-%m-%d %H:%M:%S %Z")
    s = datetime.strftime(dt, "%B {th} %Y").replace("{th}", ord(dt.day))
    out.setdefault(s, []).append(d["Text"])

out = [{"Created": k, "Text": " ".join(v)} for k, v in out.items()]
print(out)

Prints:

[
    {"Created": "July 4th 2022", "Text": "Text Random People"},
    {"Created": "August 6th 2022", "Text": "Test"},
    {"Created": "September 4th 2022", "Text": "Test"},
]
  • Related