Convert list to dictionary using linq and not worrying about duplicates

LINQ solution: // Use the first value in group var _people = personList .GroupBy(p => p.FirstandLastName, StringComparer.OrdinalIgnoreCase) .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase); // Use the last value in group var _people = personList .GroupBy(p => p.FirstandLastName, StringComparer.OrdinalIgnoreCase) .ToDictionary(g => g.Key, g => g.Last(), StringComparer.OrdinalIgnoreCase); If you prefer a non-LINQ solution then you could … Read more

Convert a JSON String to a HashMap

In recursive way: public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException { Map<String, Object> retMap = new HashMap<String, Object>(); if(json != JSONObject.NULL) { retMap = toMap(json); } return retMap; } public static Map<String, Object> toMap(JSONObject object) throws JSONException { Map<String, Object> map = new HashMap<String, Object>(); Iterator<String> keysItr = object.keys(); while(keysItr.hasNext()) { String key = … Read more

How to merge dictionaries of dictionaries?

This is actually quite tricky – particularly if you want a useful error message when things are inconsistent, while correctly accepting duplicate but consistent entries (something no other answer here does..) Assuming you don’t have huge numbers of entries, a recursive function is easiest: def merge(a, b, path=None): “merges b into a” if path is … Read more

Swift: declare an empty dictionary

var emptyDictionary = [String: String]() var populatedDictionary = [“key1”: “value1”, “key2”: “value2”] Note: if you’re planning to change the contents of the dictionary over time then declare it as a variable (var). You can declare an empty dictionary as a constant (let) but it would be pointless if you have the intention of changing it … Read more

Convert a namedtuple into a dictionary

TL;DR: there’s a method _asdict provided for this. Here is a demonstration of the usage: >>> fields = [‘name’, ‘population’, ‘coordinates’, ‘capital’, ‘state_bird’] >>> Town = collections.namedtuple(‘Town’, fields) >>> funkytown = Town(‘funky’, 300, ‘somewhere’, ‘lipps’, ‘chicken’) >>> funkytown._asdict() OrderedDict([(‘name’, ‘funky’), (‘population’, 300), (‘coordinates’, ‘somewhere’), (‘capital’, ‘lipps’), (‘state_bird’, ‘chicken’)]) This is a documented method of namedtuples, … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)