Home > Mobile >  How to slice and dice this input dictionary and get the desired output dictionary?
How to slice and dice this input dictionary and get the desired output dictionary?

Time:06-04

I have a dictionary that looks like this:

d = {
    "a": 30,
    "b": 45,
    "c": 84,
    "d": 92,
    "e": 93
    }

the story here is suppose i have a python list that has 93 items. the first 30 items (from index 0 to index 30) belongs to group "a", items from index 31 to index 45 belong to group "b". items from index 46 to index 84 belongs group "c". items from index 85 to index 92 belongs group "d". 93 rd item belongs to group "e".

so the above dictionary contains the last index of each group from this dictionary I want to create a dictionary which should look like this:

final_d = {
    "a": [0, 30],
    "b": [31, 45],
    "c": [46, 84],
    "d": [85, 92],
    "e": [93]
}

Is there an elegant way of doing this?

CodePudding user response:

Split in two list,keys and values, then put them in a zip function with both normal and shifted order.

keys,values=list(d.keys()),list(d.values())
{key:[x 1,y] for key,x,y in zip(keys,[-1] values[:-1],values)}

output:

{'a': [0, 30], 'b': [31, 45], 'c': [46, 84], 'd': [85, 92], 'e': [93, 93]}

CodePudding user response:

data = [x for x in range(93)]

d = {
    "a": 30,
    "b": 45,
    "c": 84,
    "d": 92,
    "e": 93
    }

s = 0
final_d = {}
final_data = {}
for index, value in d.items():
    e = value
    final_d[index] = [s 1,e]
    final_data[index] = data[s:e]
    s = e

print(final_d)
print(final_data)

Output:

{
 'a': [0, 30],
 'b': [31, 45],
 'c': [46, 84],
 'd': [85, 92],
 'e': [93, 93]
}

{
 'a': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 'b': [30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44],
 'c': [45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83],
 'd': [84, 85, 86, 87, 88, 89, 90, 91],
 'e': [92]
}

CodePudding user response:

One elegant way to do is by using pd.qcut:

import pandas as pd    
max_num = d[max(d, key=d.get)]
ls = [v/max_num for _, v in d.items()]
ls.insert(0, 0)
A = pd.qcut(range(max_num   1),
            ls, precision=10 ^ 5).categories.values
dict_ = {A[i] for i, _ in enumerate(d)}

Output:

dict_
{Interval(84.0, 92.0, closed='right'), Interval(-1e-15, 30.0, closed='right'), Interval(92.0, 93.0, closed='right'), Interval(45.0, 84.0, closed='right'), Interval(30.0, 45.0, closed='right')}
  • Related