Python Forum
Calculating frequency of items in a dictionary - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Calculating frequency of items in a dictionary (/thread-22780.html)



Calculating frequency of items in a dictionary - markellefultz20 - Nov-27-2019

I have a dictionary called purchases that has the payment method as the key and a dictionary containing payment types and their frequency as the values. Example formatting is as follows:
{'Credit card': {'Grocery': 3, 'Gas': 1, 'Store': 2},
'Debit card': {'Food': 2},
'Check': {'Rent': 1, 'Utilities': 1}, … }
I want to create a new dictionary with the frequency of payment methods as the key and the payment method as the values. Desired output:
[{6: ['Credit card']}, {2: ['Debit card', 'Check']}]
Here's my code so far:
artist_count = {}
for artist in artist_songs.keys():
    if artist in artist_count:
        artist_count[artist] += 1
    else:
        artist_count[artist] = 1
print(artist_count)
Currently, this outputs a dictionary with each unique payment method as a key and 1 as its value. I am having difficulty calculating the frequency of each, as well as switching the keys and the values. (I believe I can use the len function for the former, but I have not had luck with that yet.)

How can I create a new dictionary with the frequency of payment methods as the key and the payment method as the values (using python 3.6)?


RE: Calculating frequency of items in a dictionary - scidam - Nov-27-2019

You can use dict.setdefault method, e.g.

desired_output = dict()                                                                                                                                                                                                                                                       
for item in input_dict: 
    ss = sum(v for k, v in input_dict[item].items()) 
    tt = desired_output.setdefault(ss, list()) 
    tt.append(item)