Split a list into a dictionary I am trying to split my list into a dictionary and I wrote a function for it. It takes in a list and gets the list length. If the length of the list is 253 , it creates a dictionary with 26 keys - this is calculated by rounding up the number to a higher 10 (250 will create 25 keys, 251-259 will create 26 keys). Each key will store a chuck of the original list (as of now I am storing 10 elements per list).

I want to know if I can improve it more:

def limit_files(file_list, at_a_time=10):

    l = file_list
    n = len(l)
    d, r = divmod(n, at_a_time) 

    num_keys = d + 1 if r else d   
    slice = n // num_keys
    vals = (l[i:i+slice] for i in range(0, n, slice+1)) 
    dct = dict(zip(range(1,num_keys+1),vals))
    return (dct)
First of all there is a bug in your code, range(0, n, slice+1) should be range(0, n, slice) otherwise you'll miss every (slice+1)th item.
I don't understand why you re-assigned l = file_list to l here, note that simple assignments in Python don't create a copy of the object. Also don't use l as a variable name because it looks like 1(one) in many fonts.
If you're using Python 2 then use xrange() instead of range().
dict(zip(range(1,num_keys+1),vals)) can be replace with a simpler dict(enumerate(vals, start=1))
The parenthesis around (dict) in return statement are unnecessary.
slice is a built-in function, so try not to use it as a variable name. slice_size is one alternative.


Also I don't understand why you need a dict here, you can simply use a list of lists. Then the only difference will be that you'll have to start indexing at 0. Indexing is very faster than dictionary key-lookups and will also make sure the order of items is maintained.