Home > Blockchain >  Sort a python dictionary into slots of equal intervals
Sort a python dictionary into slots of equal intervals

Time:11-13

How can we sort a dictionary based on dictionary keys and put them under consistent intervals?

For example, we have the following dictionary in python

{0: 1, 10: 3, 12: 2, 19: 4, 35: 5}

So in the above example, we have keys raning from 0 - 35, and we want to put them in intervals of 10, which would imply the following:

interval 0-10 has values 1
interval 10-20 has values [3, 2, 4]
interval 20-30 has no values
interval 30-40 has values [5]

The final output should be similar to this:

{0: [1], 10: [3, 2, 4], 20: [0/null], 30: [5]

Any pythonic way of doing this?

CodePudding user response:

Using collections.defaultdict:

from collections import defaultdict

data = {0: 1, 10: 3, 12: 2, 19: 4, 35: 5}
output = defaultdict(list)
for k, v in data.items():
    output[k // 10 * 10].append(v)

>>> dict(out)
{0: [1], 10: [3, 2, 4], 30: [5]}

Edit

If you must have all keys in the resulting dict then replace the default dict with a dict that builds itself the keys:

out = {k: [] for k in (range(0, (max(data)//10*10) 1, 10))}
for k, v in data.items():
    out[k // 10 * 10].append(v)

CodePudding user response:

To add missing values maybe store a variable with last and check if the gap between them is bigger than 10:

a = {0: 1, 10: 3, 12: 2, 19: 4, 35: 5}
out = {}
last = 0
for i in a:
    b = int(i/10) * 10
    if (b - last) > 10:
        out[b-10] = [] # whatever you want it to be
    if b in out:
        out[b].append(a[i])
    else:
        out[b] = [a[i]]
    last = b

Output:

{0: [1], 10: [3, 2, 4], 20: [], 30: [5]}
  • Related