How can one make a dictionary with duplicate keys in Python?

Python dictionaries don’t support duplicate keys. One way around is to store lists or sets inside the dictionary. One easy way to achieve this is by using defaultdict: from collections import defaultdict data_dict = defaultdict(list) All you have to do is replace data_dict[regNumber] = details with data_dict[regNumber].append(details) and you’ll get a dictionary of lists.

[NSObject : AnyObject]?’ does not have a member named ‘subscript’ error in Xcode 6 beta 6

As mentioned in the Xcode 6 beta 6 release notes, a large number of Foundation APIs have been audited for optional conformance. These changes replace T! with either T? or T depending on whether the value can be null (or not) respectively. notification.userInfo is now an optional dictionary: class NSNotification : NSObject, NSCopying, NSCoding { … Read more

How to get around lack of covariance with IReadOnlyDictionary?

You could write your own read-only wrapper for the dictionary, e.g.: public class ReadOnlyDictionaryWrapper<TKey, TValue, TReadOnlyValue> : IReadOnlyDictionary<TKey, TReadOnlyValue> where TValue : TReadOnlyValue { private IDictionary<TKey, TValue> _dictionary; public ReadOnlyDictionaryWrapper(IDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(“dictionary”); _dictionary = dictionary; } public bool ContainsKey(TKey key) { return _dictionary.ContainsKey(key); } public IEnumerable<TKey> Keys … Read more

C# String replace with dictionary

If the data is tokenized (i.e. “Dear $name$, as of $date$ your balance is $amount$”), then a Regex can be useful: static readonly Regex re = new Regex(@”\$(\w+)\$”, RegexOptions.Compiled); static void Main() { string input = @”Dear $name$, as of $date$ your balance is $amount$”; var args = new Dictionary<string, string>( StringComparer.OrdinalIgnoreCase) { {“name”, “Mr … Read more

Is there anything faster than dict()?

No, there is nothing faster than a dictionary for this task and that’s because the complexity of its indexing (getting and setting item) and even membership checking is O(1) in average. (check the complexity of the rest of functionalities on Python doc https://wiki.python.org/moin/TimeComplexity ) Once you saved your items in a dictionary, you can have … Read more