Question: I have a dictionary where keys are tuples of two integers `(x,y)` and values are strings. 

How do I split this dictionary up into smaller dictionaries, where the split is determined by whether the `y`-value is greater than some treshold?

For example, say I have the keys (the dictionary values are irrelevant so I omit them here)

`(0, 2), (0, 4), (0, 10), (0, 3), (0, 11), (0, 20), (0, 8), (0, 14)`

and say I have the tresholds `0, 5, 10, 15`. 

Then, one split should consist of a dictionary with the following keys:

`(0,2), (0,4), (0,3)`

since the y-values are all greater than 0, but not greater than 5. 

Then the next dictionary should have keys

`(0,8)`

since it is greater than 0 and 5, but not greater than 10.

Then we have `(0, 10), (0, 11), (0, 14)`

since it is greater (or equal to) 0, 5, 10, but not 15.

Finally, we have `(0, 20)` by itself.

Answer: 
You can use [`collections.defaultdict`](https://docs.python.org/3.6/library/collections.html#collections.defaultdict), iterate and update keys determined by the bucket boundaries. This is a better idea than creating a variable number of variables.

```
d = {(0, 2): 1, (0, 4): 2, (0, 10): 3, (0, 3): 4,
     (0, 11): 5, (0, 20): 6, (0, 8): 7, (0, 14): 8}

L = [0, 5, 10, 15, float('inf')]  # include infinite to facilitate later comparisons

from collections import defaultdict

dd = defaultdict(dict)

for k, v in d.items():
    for i, j in zip(L, L[1:]):
        if i <= k[1] < j:
            dd[i].update({k: v})
            break

print(dd)

defaultdict(dict,
            {0: {(0, 2): 1, (0, 3): 4, (0, 4): 2},
             5: {(0, 8): 7},
             10: {(0, 10): 3, (0, 11): 5, (0, 14): 8},
             15: {(0, 20): 6}})

```

The algorithm can be improved by using `bisect` instead of iterating the boundaries in `L` sequentially.
Of course this can be written much better, but you should get the idea. Just iterate through the dict, and check the y value of the key against various conditions that you can define or generate dynamically. 

```
thing = {
    (1,2): 'a',
    (2,19): 'b'
}

d1 = {}
d2 = {}
for k, v in thing.items():
    // while iterating through the original dict, write some logic to determine how you want to split up based on the y values.
    if k[1] < 5:
        d1[k] = v
    if k[1] < 10:
        d2[k] = v

print(d1, d2)

```