karim
karim

Reputation: 681

find the frequency of key, pair of dictionaries inside of a list

I have a collection of dictionaries inside a list. And I want to find the frequency of the key,pair and then that frequency will be appended as a key of each dictioanary inside of that list.
I have gone through this, this but didn't find a solution for my problem.

The sample_list of mine is:

sample_list = [{'i': -2.0, 'q': 6.0}, {'i': 10.0, 'q': -4.0}, {'i': -5.0, 'q': -9.0},{'i': -2.0, 'q': 6.0},
{'i': -5.0, 'q': -9.0}, {'i': 4.0, 'q': -5.0}, {'i': 10.0, 'q': -4.0},{'i': 10.0, 'q': -4.0},
{'i': 4.0, 'q': 0.0}]

It is seen that

{'i': -2.0, 'q': 6.0} appeared 2 times  
{'i': 10.0, 'q': -4.0} appeared 3 times  
{'i': -5.0, 'q': -9.0} appeared 2 times  
{'i': 4.0, 'q': -5.0} appeared 1 time  
{'i': 4.0, 'q': 0.0} appeared 1 time

My desire is that the dictionaries of the sample_list will take this frequency as a key(eg: z).
New list will be

sample_list_conv = [{'i': -2.0, 'q': 6.0, 'z':2}, {'i': 10.0, 'q': -4.0, 'z':3},
{'i': -5.0,'q': -9.0, 'z':2},{'i': -2.0, 'q': 6.0, 'z':2}, {'i': -5.0, 'q': -9.0, 'z':2},
{'i': 4.0, 'q': -5.0, 'z':1},{'i': 10.0, 'q': -4.0, 'z':3}, {'i': 10.0, 'q': -4.0, 'z':3},
{'i': 4.0, 'q': 0.0, 'z':1}]

I have tried but failed and that are not worthy to add here that's why I am skipped it. Starightly if I say I need a solution for this. And also if you think that the format(sample_list) is not OK you can suggest. I need that list to plot graph using JS. And to plot heatmap I need sample_list_conv.

Upvotes: 0

Views: 97

Answers (1)

Praveen
Praveen

Reputation: 737

Create a new dict say key_count_map of key and count. Here you create key appending value of i and q.

key will look like - "i_-2.0:q_6.0"

if key is not present in key_count_map add new to key_count_map and set value to 1 if present - increment the value by 1.

You create the final result by iteration over each key and corresponding value and spliting the key into actual key

key_count_map={}

for item in sample_list:
    key = 'i_{}:q_{}'.format(item['i'], item['q'])
    if key_count_map.get(key):
        key_count_map[key] = key_count_map[key] + 1
    else:
        key_count_map[key] = 1


result = [{'i': float(key.rsplit(':')[0].rsplit('_')[1]), 'q': 
float(key.rsplit(':')[1].rsplit('_')[1]), 'z': value} for key, value in 
key_count_map.items()]

Upvotes: 1

Related Questions