Sort a list of tuples by second value, reverse=True and then by key, reverse=False

The following works with your input: d = [(‘B’, 3), (‘A’, 2), (‘A’, 1), (‘I’, 1), (‘J’, 1)] sorted(d,key=lambda x:(-x[1],x[0])) Since your “values” are numeric, you can easily reverse the sort order by changing the sign. In other words, this sort puts things in order by value (-x[1]) (the negative sign puts big numbers first) … Read more

A dictionary where value is an anonymous type in C#

You can’t declare such a dictionary type directly (there are kludges but these are for entertainment and novelty purposes only), but if your data is coming from an IEnumerable or IQueryable source, you can get one using the LINQ ToDictionary() operator and projecting out the required key and (anonymously typed) value from the sequence elements: … Read more

Convert string representing key-value pairs to Map

There is no need to reinvent the wheel. The Google Guava library provides the Splitter class. Here’s how you can use it along with some test code: package com.sandbox; import com.google.common.base.Splitter; import org.junit.Test; import java.util.Map; import static org.junit.Assert.assertEquals; public class SandboxTest { @Test public void testQuestionInput() { Map<String, String> map = splitToMap(“A=4 H=X PO=87”); assertEquals(“4”, … Read more

Easy way to convert a Dictionary to xml and vice versa

Dictionary to Element: Dictionary<string, string> dict = new Dictionary<string,string>(); XElement el = new XElement(“root”, dict.Select(kv => new XElement(kv.Key, kv.Value))); Element to Dictionary: XElement rootElement = XElement.Parse(“<root><key>value</key></root>”); Dictionary<string, string> dict = new Dictionary<string, string>(); foreach(var el in rootElement.Elements()) { dict.Add(el.Name.LocalName, el.Value); }

Comparing 2 lists consisting of dictionaries with unique keys in python

Assuming that the dicts line up like in your example input, you can use the zip() function to get a list of associated pairs of dicts, then you can use any() to check if there is a difference: >>> list_1 = [{‘unique_id’:’001′, ‘key1′:’AAA’, ‘key2′:’BBB’, ‘key3′:’EEE’}, {‘unique_id’:’002′, ‘key1′:’AAA’, ‘key2′:’CCC’, ‘key3′:’FFF’}] >>> list_2 = [{‘unique_id’:’001′, ‘key1′:’AAA’, ‘key2′:’DDD’, … Read more

How can I make the map::find operation case insensitive?

It does not by default. You will have to provide a custom comparator as a third argument. Following snippet will help you… /************************************************************************/ /* Comparator for case-insensitive comparison in STL assos. containers */ /************************************************************************/ struct ci_less : std::binary_function<std::string, std::string, bool> { // case-independent (ci) compare_less binary function struct nocase_compare : public std::binary_function<unsigned char,unsigned char,bool> { … Read more