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
useridthere are only 2 because1and2values are presenttitleis 3 as values areA,B,Ccompletedis 2 as values areTrueandFalse
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()}.