creating dynamic lists with configured values in python

Question:

Am trying to create dynamically generated lists depending on the configured value and needs a specific key for each list for example

configured value is 4
and list of numbers are [1,2,3,4,5,6,7,8,9] then this should be converted to

 key    list
-----------------
4      [1,2,3,4]
8      [5,6,7,8]
12     [9]

If configured value is 4 then always 1234 should be in first list and 5678 in second list
If the values are [1,2,3,6,7,8,9] then the result should be

key    list
-----------------
4      [1,2,3]
8      [6,7,8]
12     [9]

Tried below code and am able to create list but not the key. Also feels coded many lines to create the list.

def dicttest(data):
    data.sort()
    result = pd.DataFrame({'ids': data})
    howmany = 4
    listcount = (result['ids'].max() // howmany) + 1
    lists = []
    for x in range(listcount):
        lists.append(x * howmany)
    result['range'] = pd.cut(result.ids, lists, precision=0).astype(str)
    result = result.groupby('range').ids.apply(list).reset_index()

    return result

getting below result

range    ids
---------------
(0,4]    [1,2,3]
(4,8]    [6,7,8]
nan      [9]

It will be ok to get the result in dataframe OR dictionary with key and list of ids.

Asked By: user3625533

||

Answers:

There is an easier way to get key and perform your operation

You can simply calculate each number floor-divided by 4, and group by that. No need for pd.cut. (Though there is some complexity as show below to ensure value 4 is in row with key 4 and value 8 is in row with key 8, etc.)

def dicttest(data, howmany = 4):
    data.sort()
    result = pd.DataFrame({'sites': data})
    result['key'] = ((result['sites']-1) // howmany  + 1) * howmany 
    result = result.groupby('key').sites.apply(list)
    return result.to_dict()

The operation ((result['sites']-1) // 4 + 1) * 4 makes sure the value 4 in the list is placed in group with key 4.
The operation does (4-1) // 4 + 1) * 4 => 4.
For the 1st row, the key becomes ((1-1)// 4 + 1) * 4 = 4`

Output:

>>> dicttest([1,2,3,4,5,6,7,8,9], howmany=4)
{4: [1, 2, 3, 4], 8: [5, 6, 7, 8], 12: [9]}

Answered By: Tim
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.