Skip to content
Advertisement

How to get the count of distinct values in dictionary python

Dictionary is below

todos = [{'userId': 1, 'id': 1, 'title': 'A', 'completed': False},
     {'userId': 1, 'id': 2, 'title': 'B ', 'completed': False},
     {'userId': 1, 'id': 1, 'title': 'C', 'completed': False},
     {'userId': 1, 'id': 2, 'title': 'A', 'completed': True},
     {'userId': 2, 'id': 1,'title': 'B', 'completed': False}]

Code is below to print the values

for i in todos:
    print((i['userId']))
for i in todos:
    print((i['title']))
for i in todos:
    print((i['completed']))

Expected out is

{"userid" : 2, "title":3, "completed" : 2}

I just need the distinct count of values

  • userid there are only 2 because 1 and 2 values are present
  • title is 3 as values are A, B ,C
  • completed is 2 as values are True and False

Advertisement

Answer

you can do the following without importing pandas:

todos = [{'userId': 1, 'id': 1, 'title': 'A', 'completed': False},
     {'userId': 1, 'id': 2, 'title': 'B ', 'completed': False},
     {'userId': 1, 'id': 1, 'title': 'C', 'completed': False},
     {'userId': 1, 'id': 2, 'title': 'A', 'completed': True},
     {'userId': 2, 'id': 1,'title': 'B', 'completed': False}]
from collections import defaultdict
d = defaultdict(lambda:[])
for todo in todos:
    for k,v in todo.items():
        d[k].append(v)
d = {k:len(set(v)) for k,v in d.items()}
print(d)

output:

{'userId': 2, 'id': 2, 'title': 4, 'completed': 2}

EXPLAINATION: first you create a defaultdict the initializes default values when not existed d = defaultdict(lambda:[])

create a dict of lists instead of dict of lists

for todo in todos:
    for k,v in todo.items():
        d[k].append(v)

then you extract the uniquevalues with set and measure the length {k:len(set(v)) for k,v in d.items()}.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement