Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a dictionary of counts of items in a list

I have a List containing a bunch of strings that can occur more than once. I would like to take this list and build a dictionary of the list items as the key and the count of their occurrences as the value.

Example:

List<string> stuff = new List<string>();
stuff.Add( "Peanut Butter" );
stuff.Add( "Jam" );
stuff.Add( "Food" );
stuff.Add( "Snacks" );
stuff.Add( "Philosophy" );
stuff.Add( "Peanut Butter" );
stuff.Add( "Jam" );
stuff.Add( "Food" );

and the result would be a Dictionary containing:

"Peanut Butter", 2
"Jam", 2
"Food", 2
"Snacks", 1
"Philosophy", 1

I have a way to do this, but it doesn't seem like I'm utilizing the good stuff in C# 3.0

public Dictionary<string, int> CountStuff( IList<string> stuffList )
{
    Dictionary<string, int> stuffCount = new Dictionary<string, int>();

    foreach (string stuff in stuffList) {
        //initialize or increment the count for this item
        if (stuffCount.ContainsKey( stuff )) {
            stuffCount[stuff]++;
        } else {
            stuffCount.Add( stuff, 1 );
        }
    }

    return stuffCount;
}
like image 767
Ryan Ische Avatar asked Mar 26 '09 19:03

Ryan Ische


People also ask

How do you count the number of items in a list?

You can count the number of elements in a list using the len(list) function. You need to find the list length for various purposes, For example: Iterating through the list and accessing each item.

How do I make a dictionary out of a list?

To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.

How do you count the number of items in a dictionary?

method 3: Use len() function to count the number of keys in a dictionary. The len() function is used to find the length of objects. It returns the total number of items. In dictionaries, the items are stored in the form of key-value pairs which means that the total number of items and keys are equal.

Can you convert a list into a dictionary?

To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.


3 Answers

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);
like image 51
casperOne Avatar answered Oct 18 '22 10:10

casperOne


I would have made a specialized List, that backed by the Dictionary and the add method would test for membership and increase count if found.

sorta like:

public class CountingList
{
    Dictionary<string, int> countingList = new Dictionary<string, int>();

   void Add( string s )
   {
        if( countingList.ContainsKey( s ))
             countingList[ s ] ++;
        else
            countingList.Add( s, 1 );
   }
}
like image 23
sfossen Avatar answered Oct 18 '22 09:10

sfossen


One idea would be to give the dictionary a default value of zero, so you wouldn't have to special case the first occurrence.

like image 31
MarkusQ Avatar answered Oct 18 '22 09:10

MarkusQ