Home > Software design >  Python3: Get count for same dictionaries within list
Python3: Get count for same dictionaries within list

Time:09-07

I have a list of dictionaries and want to get the unique dictionaries with count. i.e

[{'Basic': 100},
{'Basic': 100},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 100},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 200}]

Out put should be like

{'Basic': 100} -> 3
{'Basic': 100, 'Food Allowance': 1000} -> 3
{'Basic': 200} -> 1

OR

[index_no] -> count

CodePudding user response:

A quick and dirty solution would be to loop over the list of dictionaries and save each unique one and keep a counter. Something like this:

def count_and_set_dict(dict):
    set_dict = []
    count_dict = []

    for d in dict:
        if d not in set_dict:
            set_dict.append(d)
            count_dict.append(1)
        else:
            count_dict[set_dict.index(d)]  = 1

    for i in range(len(set_dict)):
        print(f"{set_dict[i]} --> {count_dict[i]}")

dicts = [{'Basic': 100},
{'Basic': 100},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 100},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 200}]

count_and_set_dict(dicts)

Output

{'Basic': 100} --> 3
{'Basic': 100, 'Food Allowance': 1000} --> 3
{'Basic': 200} --> 1

CodePudding user response:

My approach is getting unique dictionaries in the list and counting the elements in the original list by count()

dictlist = [{'Basic': 100},
{'Basic': 100},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 100},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 200}]

unique_dictlist = list(map(dict, set(tuple(sorted(sub.items())) for sub in dictlist))) #to get only unique values.
for d in unique_dictlist:
    print(d,"-->",dictlist.count(d))

result:

{'Basic': 200} -> 1
{'Basic': 100, 'Food Allowance': 1000} -> 3
{'Basic': 100} -> 3

CodePudding user response:

Using collections.Counter

  • Dictionary is not hashable so must convert each to a tuple

Code

from collections import Counter

lst = [{'Basic': 100},
{'Basic': 100},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 100},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 200}]

# Output count of each dictionary
print(Counter([tuple(d.items()) for d in lst]))

Output

Counter({(('Basic', 100),): 3,
         (('Basic', 100), ('Food Allowance', 1000)): 3,
         (('Basic', 200),): 1})

CodePudding user response:

import ast
tmp = {}
for i in set([str(d) for d in df1]):
    tmp[i] = df1.count(ast.literal_eval(i))

Output:

{"{'Basic': 100, 'Food Allowance': 1000}": 3,
 "{'Basic': 100}": 3,
 "{'Basic': 200}": 1}

CodePudding user response:

You can use collections.Counter, however, it requires the list elements to be hashable, which dictionaries are clearly not. One solution might be converting your dictionaries to 'string dictionaries':

from collections import Counter
Counter([str(i) for i in your_list])

will return:

Counter({"{'Basic': 100}": 3,
     "{'Basic': 100, 'Food Allowance': 1000}": 3,
     "{'Basic': 200}": 1})
  • Related