Flask restful model with variable keys

630 Views Asked by At

As a part of my RESTful API I found myself needing to return a json with "variable" keys, I'll try to make things more clear with a simple example:

I have different groups, each group has a group_id, so the expected return would be:

{
    1: {
         "name": "first_group_name",
         ...
       },
    5: {
         "name": "second_group_name",
         ...
       }
}

As you can see, the keys (group_ids) in the root json are not something I can hard-code in my model, all I know is they are integers. Can anyone help with a solution to this problem?

1

There are 1 best solutions below

1
On

I am not sure this is what you need but you can do something like this:

return_values = {}
group_ids = [1, 2, 3, 4]
for g_id in group_ids:
    return_values[g_id] = { "name": "%s_group_name"%i }

print(return_values)

#{1: {'name': 'group_1'}, 2: {'name': 'group_2'}, 3: {'name': 'group_3'}, 4: {'name': 'group_4'}}

if you are using you can modify the code as you want.