Home > Mobile >  How to loop through a dictionary values and get all numbers between two numbers?
How to loop through a dictionary values and get all numbers between two numbers?

Time:07-15

I have a dictionary storing machine learning prediction probabilities. The keys of the dictionary are the indices of predicted instances and the values are lists containing class probabilities. I want to create a new dictionary to store all class probabilities that are between two numbers (0.48 and 0.55). With the code below I did not get the expected result as it seems my for loop does not iterate through all the values of my dictionary.

d={348: [0,0,0,0.5,0,0,0.49], 349: [0,0,0.3,0.48,0.49,0.55,0.9], 350: 
[0,0,0.3,0.45,0.0,0.52,0.8]} 

dt={}
for i in d:
  for index, value in enumerate(d[i]):
    if value >= 0.45 and value <= 0.55:
      dt={i: {(str(index   1)): [value]} }
print(dt) 

My output is now is only:

{350: {'6': 0.52}}. 

However, I want to get all the numbers from all the values list between 0.48 and 0.55 and get the keys associated with the numbers selected as well as the indices of the numbers in the values list. My desired output is below:

{348: {'4': 0.5, '7': 0,49}, 349: {'4': 0.48, '5': 0.49, '6', 0.55}, 350: {'4': 0.45, 
'6': 0.52}

CodePudding user response:

You can use dict-comprehension:

d = {
    348: [0, 0, 0, 0.5, 0, 0, 0.49],
    349: [0, 0, 0.3, 0.48, 0.49, 0.55, 0.9],
    350: [0, 0, 0.3, 0.45, 0.0, 0.52, 0.8],
}

out = {
    k: {str(i): x for i, x in enumerate(v, 1) if 0.45 <= x <= 0.55}
    for k, v in d.items()
}
print(out)

Prints:

{
    348: {"4": 0.5, "7": 0.49},
    349: {"4": 0.48, "5": 0.49, "6": 0.55},
    350: {"4": 0.45, "6": 0.52},
}

CodePudding user response:

dt = {}
for i, l in d.items():
    dt[i] = {str(j 1):value for j, value in enumerate(l) if value >= 0.45 and value <= 0.55}

What you were doing wrong is that dt was being created each loop.

CodePudding user response:

  • Firstly, you are overwriting your results dictionary everytime a matching value is found, which is why the result is only a dictionary with one key

  • Second, instead of doing for i in d, why not use .items() since you are going to be using both, the key and the value of the dictionary?

Try this code:

d = {348: [0, 0, 0, 0.5, 0, 0, 0.49], 349: [0, 0, 0.3, 0.48, 0.49, 0.55, 0.9], 
     350: [0, 0, 0.3, 0.45, 0.0, 0.52, 0.8]} 

dt = {}

for key, value in d.items():
    dt[key] = {}
    for index, v in enumerate(value):
        if 0.45 <= v <= 0.55:
            dt[key][str(index   1)] = v
print(dt)
  • Related