Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

creating dynamic lists with configured values in python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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).reset_index()
    return result

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.

Output:

>>> dicttest([1,2,3,4,5,6,7,8,9], howmany=4)
     key         sites
0      4  [1, 2, 3, 4]
1      8  [5, 6, 7, 8]
2     12           [9]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading