Using a Dictionary to Count the Items in a List

Count items in list and make it a dictionary

This is exactly what a Counter is for.

>>> from collections import Counter
>>> Counter(['tango', 'bravo', 'tango', 'alpha', 'alpha'])
Counter({'tango': 2, 'alpha': 2, 'bravo': 1})

You can use the Counter object just like a dictionary, because it is a child class of the builtin dict. Excerpt from the docs:

class Counter(__builtin__.dict)

Dict subclass for counting hashable items. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values.

edit:

As requested, here's another way:

>>> names = ['tango', 'bravo', 'tango', 'alpha', 'alpha']
>>> d = {}
>>> for name in names:
... d[name] = d.get(name, 0) + 1
...
>>> d
{'bravo': 1, 'tango': 2, 'alpha': 2}

How do you count elements of a list that's inside a dictionary?

It is what you expected?

files = {"f1": ["cat", "dog", "mouse"],
"f2": ["rat", "elephant", "tiger", "dog"]}

word = "dog"
counter = 0

for values in files.values():
if word in values:
print(True)
counter +=1
else:
print(False)

print(counter)

If a dictionary value is a list, how to count item in that list?

You can try something like this:

dict = {'A': ['red', 'red', 'blue'],
'B': ['red', 'green'],
'C': ['blue', 'green']}
new_dict = {}

for key in dict.keys():
new_dict[key] = {}
for item in dict[key]:
if item not in new_dict[key].keys():
new_dict[key][item] = 1
else:
new_dict[key][item] += 1

print(new_dict)

The output will be:

{'A': {'red': 2, 'blue': 1}, 'B': {'red': 1, 'green': 1}, 'C': {'blue': 1, 'green': 1}}

how to count the number of items in a list which is nested in a dictionary?

You were close, you were just checking the length of the wrong variable...

favourite_languages = {
'Joe': ['French'],
'Jim': ['Spanish', 'Portugese'],
'Alan':['German', 'Swedish']
}

for name, langs in favourite_languages.items():
if not len(langs):
print(f"{name} has no favorite language.")
elif len(langs) == 1:
print(f"{name}'s favourite language is {langs}")
else:
print(f"{name}'s favourite languages are {langs}")

Building a dictionary of counts of items in a list

You can use the group clause in C# to do this.

List<string> stuff = new List<string>();
...

var groups =
from s in stuff
group s by s into g
select new {
Stuff = g.Key,
Count = g.Count()
};

You can call the extension methods directly as well if you want:

var groups = stuff
.GroupBy(s => s)
.Select(s => new {
Stuff = s.Key,
Count = s.Count()
});

From here it's a short hop to place it into a Dictionary<string, int>:

var dictionary = groups.ToDictionary(g => g.Stuff, g => g.Count);

Count elements in a list without using Counter

Separating the keys and values is a lot of effort when you could just build the dict directly. Here's the algorithm. I'll leave the implementation up to you, though it sort of implements itself.

  1. Make an empty dict
  2. Iterate through the list
  3. If the element is not in the dict, set the value to 1. Otherwise, add to the existing value.

See the implementation here:

https://stackoverflow.com/a/8041395/4518341



Related Topics



Leave a reply



Submit