0

My Input JSON data:

{
    "data": [
        {
            "config": "current",
            "id": "0"
        },
        {
            "config": "current",
            "id": "1"
        },
        {
            "config": "current",
            "id": "2"
        },
        {
            "config": "current",
            "id": "3"
        },
        {
            "config": "previous",
            "id": "4",
        },
        {
            "config": "previous",
            "id": "5"
        },
        {
            "config": "current",
            "id": "6"
        }
    ]
}

I want to form a dictionary of lists out of above input data based on common key/value pair:

{
    "current": ["0", "1", "2", "3", "6"],
    "previous": ["4", "5"]
}

How can this be achieved using python?

wjandrea
  • 28,235
  • 9
  • 60
  • 81

2 Answers2

1

Assuming you already know how to parse JSON, you can do this:

d = {
    "data": [
        {"config": "current", "id": "0"},
        {"config": "current", "id": "1"},
        {"config": "current", "id": "2"},
        {"config": "current", "id": "3"},
        {"config": "previous", "id": "4"},
        {"config": "previous", "id": "5"},
        {"config": "current", "id": "6"}]
    }

result = {}
for d0 in d['data']:
    ids = result.setdefault(d0['config'], [])
    ids.append(d0['id'])

print(result)
# -> {'current': ['0', '1', '2', '3', '6'], 'previous': ['4', '5']}
  • dict.setdefault() is used to get the id list if it exists, or if not, set it to a default, which is an empty list here. It's functionally the same as this:

    config = d0['config']
    if config not in result:
        result[config] = []
    result[config].append(d0['id'])
    

    You could also use collections.defaultdict(list) to do the same thing even more easily.

    [This explanation is taken from my answer here.]

wjandrea
  • 28,235
  • 9
  • 60
  • 81
0
jsn = {
    "data": [
        {"config": "current", "id": "0"},
        {"config": "current", "id": "1"},
        {"config": "current", "id": "2"},
        {"config": "current", "id": "3"},
        {"config": "previous", "id": "4",},
        {"config": "previous", "id": "5"},
        {"config": "current", "id": "6"}
    ]
}

current = [x["id"] for x in jsn["data"] if x["config"] == "current"]
previous = [x["id"] for x in jsn["data"] if x["config"] == "previous"]

res = {"current": current, "previous": previous}

print(res) # {'current': ['0', '1', '2', '3', '6'], 'previous': ['4', '5']}

Or the same algorigthm with a function:

def get_ids(json_string, key):
    return [x["id"] for x in json_string["data"] if x["config"] == key]

res = { 
    "current": get_ids(jsn, "current"), 
    "previous": get_ids(jsn, "previous") 
    }

print(res) # {'current': ['0', '1', '2', '3', '6'], 'previous': ['4', '5']}
Yuri Khristich
  • 13,448
  • 2
  • 8
  • 23