Peeriich
Peeriich

Reputation: 21

Percentile from dictionary list

I am having an issue with extracting values from a dictionary. I have created this dictionary from a CSV file. However, I got stuck when I tried to extract percentile value for each key in the dictionary. My dictionary looks like this:

dic = {'2008': [10,20, 56, 30, 57], '1950': [10.1,59.6, 56, 30.8, 99.6]}. 

I'd like to have my output as:

1950,56.0
2008,30.0

What I tried so far is:

import numpy as np

dic ={}

pert ={'key':'value'}
for k in dic.keys():

    for items in dic[k]:
    p = np.percentile(items,95)
    pert[k] = p

Upvotes: 2

Views: 2994

Answers (1)

Mike Müller
Mike Müller

Reputation: 85482

This make a dictionary with 95th percentiles:

dic = {'2008': [10,20, 56, 30, 57], '1950': [10.1,59.6, 56, 30.8, 99.6]}
res = {k: np.percentile(v, 95) for k, v in dic.items()}

The content of res:

{1950': 91.599999999999994, '2008': 56.799999999999997}

Get the median with:

>>> {k: np.median(v) for k, v in dic.items()}
{'1950': 56.0, '2008': 30.0}

Upvotes: 4

Related Questions