Apologies for the wording of this question. I have the beneath list containing sub-objects that also contains key, value pairs.
l = [{'melissa': ["power"]}, {'Linda': ["power", "a"]}, {'Rachel': ["power", "document"]}]
This is my current solution that counts the amount of occurrences of strings in each objects list as expected:
cnt = {}
for i in l:
for x in i.values():
for j in x:
if j not in cnt:
cnt[j] = 1
else:
cnt[j] += 1
final = list(map(list, cnt.items()))
print(final)
Output:
final = [['power', 3], ['a', 1], ['document', 1]]
Is there a better/more succinct method of doing this?
I would still like the output to be a list of sub-lists.
Thanks
Use collections.Counter
:
from collections import Counter
l = [
{"melissa": ["power"]},
{"Linda": ["power", "a"]},
{"Rachel": ["power", "document"]},
]
out = Counter(i for d in l for lst in d.values() for i in lst)
out = list(map(list, out.items()))
print(out)
Prints:
[['power', 3], ['a', 1], ['document', 1]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.