How to sort a list of dictionaries by a value of the dictionary in Python?

The sorted() function takes a key= parameter newlist = sorted(list_to_be_sorted, key=lambda d: d[‘name’]) Alternatively, you can use operator.itemgetter instead of defining the function yourself from operator import itemgetter newlist = sorted(list_to_be_sorted, key=itemgetter(‘name’)) For completeness, add reverse=True to sort in descending order newlist = sorted(list_to_be_sorted, key=itemgetter(‘name’), reverse=True)

Elegant way of counting occurrences in a java collection

Now let’s try some Java 8 code: static public Map<String, Integer> toMap(List<String> lst) { return lst.stream() .collect(HashMap<String, Integer>::new, (map, str) -> { if (!map.containsKey(str)) { map.put(str, 1); } else { map.put(str, map.get(str) + 1); } }, HashMap<String, Integer>::putAll); } static public Map<String, Integer> toMap(List<String> lst) { return lst.stream().collect(Collectors.groupingBy(s -> s, Collectors.counting())); } I think this … Read more

Parse JSON object with string and value only

You need to get a list of all the keys, loop over them and add them to your map as shown in the example below: String s = “{menu:{\”1\”:\”sql\”, \”2\”:\”android\”, \”3\”:\”mvc\”}}”; JSONObject jObject = new JSONObject(s); JSONObject menu = jObject.getJSONObject(“menu”); Map<String,String> map = new HashMap<String,String>(); Iterator iter = menu.keys(); while(iter.hasNext()){ String key = (String)iter.next(); String … Read more

How to generate all combination from values in dict of lists in Python

If you want to keep the key:value in the permutations you can use: import itertools keys, values = zip(*my_dict.items()) permutations_dicts = [dict(zip(keys, v)) for v in itertools.product(*values)] this will provide you a list of dicts with the permutations: print(permutations_dicts) [{‘A’:’D’, ‘B’:’F’, ‘C’:’I’}, {‘A’:’D’, ‘B’:’F’, ‘C’:’J’}, … ] Disclaimer: not exactly what the OP was asking, … Read more

How to implement ConcurrentHashSet in .Net

I just ran into a similar scenario (“I am interested in a fast Add and Contains and Remove”) and implemented this sucker: using System.Collections.Generic; using System.Threading; namespace BlahBlah.Utilities { public class ConcurrentHashSet<T> : IDisposable { private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); private readonly HashSet<T> _hashSet = new HashSet<T>(); #region Implementation of ICollection<T> …ish public … Read more