In 2.7 and 3.1, there is the special Counter (dict subclass) for this purpose.
>>> from collections import Counter
>>> Counter(['apple','red','apple','red','red','pear'])
Counter({'red': 3, 'apple': 2, 'pear': 1})
Answer from Odomontois on Stack OverflowIn 2.7 and 3.1, there is the special Counter (dict subclass) for this purpose.
>>> from collections import Counter
>>> Counter(['apple','red','apple','red','red','pear'])
Counter({'red': 3, 'apple': 2, 'pear': 1})
I like:
counts = dict()
for i in items:
counts[i] = counts.get(i, 0) + 1
.get allows you to specify a default value if the key does not exist.
I am trying to count how many times "yes" value appears in the done key but every time i rune the script i end up with a 0 can someone help please ?
list=[{"task":"walk dog", "done":"yes"},
{"task":"talk", "done":"yes"},
{"task":"sleep", "done":"yes"},
{"task":"eat", "done":"no"},
{"task":"chicken", "done":"yes"},
{"task":"smoke", "done":"yes"}
]
c = 0
for item in list:
if list[1] == "yes":
c= c+1
print(c)Hi,
let's assume I have the following list:
a = [{'key': 'value1', 'key2': 'value2'},
{'key': 'value1', 'key2': 'value2'},
{'key': 'value3', 'key4': 'value5'}]
I would like to now get the count of each dictionary in this list, as a key: value in the dict.
Example output:
[{'key': 'value3', 'key4': 'value5', 'count': 1},
{'key': 'value1', 'key2': 'value2', 'count': 2}]Is there are a smarter way than some sort of loop? It should work but I would like to keep my O() down as much as possible.
I know that there are some examples for lists of strings or integers but they are all hashable types which dictionaries are not.
Problem with your code is that you seem to iterate on all letters of the word. letter[0] is a substring of the letter (which is a string).
You'd have to do it more simply, no need for a double loop, take each first letter of your words:
for word in text:
if word: # to filter out empty strings
first_letter = word[0]
But once again collections.Counter taking a generator comprehension to extract first letter is the best choice and one-liner (with an added condition to filter out empty strings):
import collections
c = collections.Counter(x[0] for x in ["banana","ball", "cat", "", "hat"] if x)
c is now a dict: Counter({'b': 2, 'h': 1, 'c': 1})
one variant to insert None instead of filtering out empty values would be:
c = collections.Counter(x[0] if x else None for x in ["banana","ball", "cat", "", "hat"])
my_list=["banana","ball", "cat", "hat"]
my_dict = dict()
for word in my_list:
try:
my_dict[word[0]] += 1
except KeyError:
my_dict[word[0]] = 1
This increases the value of the key by 1 for the already existing key, and if they key has not been found before it creates it with the value 1
Alternative:
my_list=["banana","ball", "bubbles", "cat", "hat"]
my_dict = dict()
for word in my_list:
if word[0] in my_dict.keys():
my_dict[word[0]] += 1
else:
my_dict[word[0]] = 1
if you have in your list only dictionaries than you can use the buid-in function len:
len(my_list)
if you have also other objects than dictionaries in your list than you can filter your list to keep only the dictionaries in a list comprehension than use the same len method:
len([e for e in my_list if isinstance(e, dict)])
or you can use the buit-in funcion sum:
sum(1 for e in my_list if isinstance(e, dict))
Try this:
dataList = [[0, {"1":1}, {"5":5}], {'a': 1,'b':2,'c':3}, {'a':3,'b': 3,'c':5}, {'a': 5,'b': 4,'c': 5}, [2, [2, {"100":2, "120":{100:1}}]]]
def numDict(li):
count = 0
if isinstance(li, str):
return 0
if isinstance(li, dict):
return return numDict(li.values()) + numDict(li.keys()) + 1
try:
for i in li:
count = count + numDict(i)
except TypeError:
return 0
return count
print(numDict(dataList))
It handles nested dictionaries too. I am using recursive and it has a limit on the number of recursive call it can make. If you exceed a certain depth of nested dictionaries, then you will get following error:
RecursionError: maximum recursion depth exceeded while calling a Python object
Output:
7