Python Forum
Calculating frequency of items in a dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Calculating frequency of items in a dictionary
#1
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)?
Reply
#2
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) 
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to assign items from a list to a dictionary CompleteNewb 3 1,535 Mar-19-2022, 01:25 AM
Last Post: deanhystad
  finding items/comparison in/with a dictionary AGC 17 7,032 Apr-02-2018, 08:30 PM
Last Post: AGC
  Python find the minimum length of string to differentiate dictionary items zydjohn 3 3,560 Mar-03-2018, 05:23 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020