python tuple to dict
Try: >>> t = ((1, ‘a’),(2, ‘b’)) >>> dict((y, x) for x, y in t) {‘a’: 1, ‘b’: 2}
Try: >>> t = ((1, ‘a’),(2, ‘b’)) >>> dict((y, x) for x, y in t) {‘a’: 1, ‘b’: 2}
Quite simple with a closure: def map = [ ‘iPhone’:’iWebOS’, ‘Android’:’2.3.3′, ‘Nokia’:’Symbian’, ‘Windows’:’WM8′ ] map.each{ k, v -> println “${k}:${v}” }
Yes, that’s guaranteed. Moreover, *begin() gives you the smallest and *rbegin() the largest element, as determined by the comparison operator, and two key values a and b for which the expression !compare(a,b) && !compare(b,a) is true are considered equal. The default comparison function is std::less<K>. The ordering is not a lucky bonus feature, but rather, … Read more
Use reduce() to traverse the dictionary: from functools import reduce # forward compatibility for Python 3 import operator def getFromDict(dataDict, mapList): return reduce(operator.getitem, mapList, dataDict) and reuse getFromDict to find the location to store the value for setInDict(): def setInDict(dataDict, mapList, value): getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value All but the last element in mapList is needed … Read more
As of Swift 2.0, Dictionary’s values property now returns a LazyMapCollection instead of a LazyBidirectionalCollection. The Array type knows how to initialise itself using this abstract collection type: let colors = Array(colorsForColorSchemes.values) Swift’s type inference already knows that these values are UIColor objects, so no type casting is required, which is nice!
Swift 4+ Good news! Swift 4 includes a mapValues(_:) method which constructs a copy of a dictionary with the same keys, but different values. It also includes a filter(_:) overload which returns a Dictionary, and init(uniqueKeysWithValues:) and init(_:uniquingKeysWith:) initializers to create a Dictionary from an arbitrary sequence of tuples. That means that, if you want … Read more
A nested dict is a dictionary within a dictionary. A very simple thing. >>> d = {} >>> d[‘dict1’] = {} >>> d[‘dict1’][‘innerkey’] = ‘value’ >>> d[‘dict1’][‘innerkey2’] = ‘value2’ >>> d {‘dict1’: {‘innerkey’: ‘value’, ‘innerkey2’: ‘value2’}} You can also use a defaultdict from the collections package to facilitate creating nested dictionaries. >>> import collections >>> … Read more
Use: from collections import defaultdict d = defaultdict(lambda: defaultdict(int)) This will create a new defaultdict(int) whenever a new key is accessed in d.
Using dict.pop: d = {‘some’: ‘data’} entries_to_remove = (‘any’, ‘iterable’) for k in entries_to_remove: d.pop(k, None)
has_key was removed in Python 3. From the documentation: Removed dict.has_key() – use the in operator instead. Here’s an example: if start not in graph: return None