working on it ...

Filters

Explore Public Snippets

Sort by

Found 1,636 snippets matching: dictionary

    public by cghersi  247002  1  6  1

    Calculate the occurrences of words in Rss feed

    Creates a dictionary with keys=words and values=occurrences of that word in the given Rss (specified by the URL). The caller should specify the maximum number of items in the returning dictionary and, optionally, the minimum length of the words that will be added to the output.
    public static Dictionary<string, int> ComputeWordsOccurrencesInRss(string url, int maxItems, int minLenOfAcceptedWords = 1)
    {
      Dictionary<string, int> occurrences = new Dictionary<string, int>();
    
      IList<RssReader.RssItem> singleRssResult = RssReader.ReadRss(url, maxItems, true);
      string[] splitted = null;
      foreach (RssReader.RssItem rss in singleRssResult)
      {
        List<string> words = new List<string>();
    
        //split title in words:
        splitted = StringHelper.SplitIntoWords(rss.Title);
        if (splitted != null)
          words.AddRange(splitted);
    
        //split summary in words:
        splitted = StringHelper.SplitIntoWords(rss.Summary);
        if (splitted != null)
          words.AddRange(splitted);
    
        //compute occurrences of words:
        for (int w = 0; w < words.Count; w++)
        {
          string word = words[w].ToLower();
          if (word.Length < minLenOfAcceptedWords)
            continue;
          if (occurrences.ContainsKey(word))
            occurrences[word]++;
          else
            occurrences.Add(word, 1);
        }
      }
    
      return occurrences;
    }
    

    public by vietkute02  16485  105  6  2

    convert suds response to dictionary

    from suds.sudsobject import asdict
    
    def recursive_asdict(d):
        """Convert Suds object into serializable format."""
        out = {}
        for k, v in asdict(d).iteritems():
            if hasattr(v, '__keylist__'):
                out[k] = recursive_asdict(v)
            elif isinstance(v, list):
                out[k] = []
                for item in v:
                    if hasattr(item, '__keylist__'):
                        out[k].append(recursive_asdict(item))
                    else:
                        out[k].append(item)
            else:
                out[k] = v
        return out
    
    def suds_to_json(data):
        return json.dumps(recursive_asdict(data))

    public by lbottaro  5217  0  7  0

    How to populate a dictionary in python

    This code shows how to populate a dictionary, using the built-in method setdefault. If the key does not exist, it will be created setting its value too. Otherwise the new value will be appended to the existing ones. In this way the key existence in automatically checked by python during run time.
    myDict= dict()
    keyName = 'myNewKey'
    txtData = 'some data'
    myDict.setdefault(keyName,[]).append(txtData)

    public by lbottaro  3840  0  6  0

    How to check key presence in a python dictionary

    This is the simplest way to check if a given key is present in a dictionary
    dic = dict()
    
    dic['a'] = 'foo'
    dic['gg'] = 'bar'
    if 'a' in dic:
      print 'Found'
    else:
      print 'Not found'
     
    

    public by lbottaro  3074  1  8  0

    How to create a Set<T> map in java

    This simple snippet shows how to instantiate a HashSet map
    import java.util.*;
    
    public class HashSetGenerator {
        public static void main(String[] args) {
            Set<String> s = new HashSet<String>();
            for (String a : args)
                   s.add(a);
                   System.out.println(s.size() + " contains words: " + s);
        }
    }                                                

    public by sTiLL-iLL @ SniPitz-KND  2411  1  7  17

    Simple JS Dictionary data structure

    look it up chuck!
    // dictionary structure
    
    function Diktionary(startValues) {
    
      this.values = startValues || {};
    
    }
    
    
    
    Diktionary.prototype.store = function(name, value) {
    
      this.values[name] = value;
    
    };
    
    
    Diktionary.prototype.lookup = function(name) {
    
      return this.values[name];
    
    };
    
    
    Diktionary.prototype.contains = function(name) {
    
      return (Object.prototype.hasOwnProperty.call(this.values, name) && Object.prototype.propertyIsEnumerable.call(this.values, name));
    
    };
    
    
    Diktionary.prototype.each = function(action) {
      
      forEachIn(this.values, action);
    
    };
    
    
    function forEachIn(object, action) {
    
        try {
    
            for (var property in object) {
    
                if (Object.prototype.hasOwnProperty.call(object, property)) {
    
                    action(property, object[property]);
                }
            }
    
        }
        catch (e) {
    
            if (e != Break) {
    
                throw e;
            }
        }
    
    }

    public by lbottaro  2562  1  6  0

    How to create a Java HashMap and iterate through keys and values

    This is how to simply create a templated Map, using HashMap and loop through its keys and values
    final Map<String, Object> myMap = new HashMap<String, Object>();
            myMap.put("key1", "true");
            myMap.put("key2", "123");
    
    for (Map.Entry<String, Object> entry : myMap.entrySet())
    {
        System.out.println(entry.getKey() + "/" + entry.getValue());
    }                                                          

    public by cghersi  3348  1  5  0

    Retrieve the keys of a dictionary sorted by values

    Returns the key set ordered by the values.
    public static List<string> SortDictionaryByValue(Dictionary<string, int> input, int maxResults, bool ascend = false)
    {
      if (input == null)
        return new List<string>();
      if (ascend)
        return input.OrderBy((e) => e.Value).Take(maxResults).Select(e => e.Key).ToList();
      else
        return input.OrderByDescending((e) => e.Value).Take(maxResults).Select(e => e.Key).ToList();
    }
    

    public by mprisznyak  2810  2  5  4

    Reverse a dictionary

    How to swap keys and values easily
    # you have some data mapped onto each other 
    d = {"one": 1, "two": 2, "three": 3}
    # if you want the reverse map
    # then use a dictionary comprehension from Python 2.7 onwards
    d_reversed =  {value:key for key, value in d.items()}
    # or use a list comprehension for earlier Python versions:
    d_reversed_old = dict([(value,key) for key, value in d.items()])
    print d, d_reversed, d_reversed_old            

    public by BrentHoover  1874  0  4  0

    Dictionary based logging config

    Dictionary based logging config: dict_logging.py
    import logging
    from logging.config import dictConfig
    
    from logsettings import LOG_SETTINGS
    
    dictConfig(LOG_SETTINGS)
    logger = logging.getLogger('reservation.requests')
    logger.setLevel(logging.DEBUG)
    
    
    • Public Snippets
    • Channels Snippets