defaultdict

Surprising results with Python timeit: Counter() vs defaultdict() vs dict()

耗尽温柔 提交于 2019-11-26 23:14:15
I obtained very surprising results with timeit, can someone tell me if I am doing something wrong ? I am using Python 2.7. This is the contents of file speedtest_init.py: import random to_count = [random.randint(0, 100) for r in range(60)] These are the contents of speedtest.py: __author__ = 'BlueTrin' import timeit def test_init1(): print(timeit.timeit('import speedtest_init')) def test_counter1(): s = """\ d = defaultdict(int); for i in speedtest_init.to_count: d[i] += 1 """ print(timeit.timeit(s, 'from collections import defaultdict; import speedtest_init;')) def test_counter2(): print

Checking a nested dictionary using a dot notation string “a.b.c.d.e”, automatically create missing levels

瘦欲@ 提交于 2019-11-26 23:06:13
This one is blowing my mind. Given the following dictionary: d = {"a":{"b":{"c":"winning!"}}} I have this string (from an external source, and I can't change this metaphor). k = "a.b.c" I need to determine if the dictionary has the key 'c', so I can add it if it doesn't. This works swimmingly for retrieving a dot notation value: reduce(dict.get, key.split("."), d) but I can't figure out how to 'reduce' a has_key check or anything like that. My ultimate problem is this: given "a.b.c.d.e", I need to create all the elements necessary in the dictionary, but not stomp them if they already exist. If

Can't pickle defaultdict

╄→гoц情女王★ 提交于 2019-11-26 22:20:45
I have a defaultdict that looks like this: dict1 = defaultdict(lambda: defaultdict(int)) The problem is, I can't pickle it using cPickle. One of the solution that I found here is to use module-level function instead of a lambda. My question is, what is module-level function? How can I use the dictionary with cPickle? sloth In addition to Martijn's explanation : A module-level function is a function which is defined at module level, that means it is not an instance method of a class, it's not nested within another function, and it is a "real" function with a name, not a lambda function. So, to

Python defaultdict and lambda

淺唱寂寞╮ 提交于 2019-11-26 15:17:52
问题 In someone else's code I read the following two lines: x = defaultdict(lambda: 0) y = defaultdict(lambda: defaultdict(lambda: 0)) As the argument of defaultdict is a default factory, I think the first line means that when I call x[k] for a nonexistent key k (such as a statement like v=x[k]), the key-value pair (k,0) will be automatically added to the dictionary, as if the statement x[k]=0 is first executed. Am I correct? And what about y? It seems that the default factory will create a

Can't pickle defaultdict

自古美人都是妖i 提交于 2019-11-26 09:36:06
问题 I have a defaultdict that looks like this: dict1 = defaultdict(lambda: defaultdict(int)) The problem is, I can\'t pickle it using cPickle. One of the solution that I found here is to use module-level function instead of a lambda. My question is, what is module-level function? How can I use the dictionary with cPickle? 回答1: In addition to Martijn's explanation: A module-level function is a function which is defined at module level, that means it is not an instance method of a class, it's not

`if key in dict` vs. `try/except` - which is more readable idiom?

孤街浪徒 提交于 2019-11-26 09:26:35
问题 I have a question about idioms and readability, and there seems to be a clash of Python philosophies for this particular case: I want to build dictionary A from dictionary B. If a specific key does not exist in B, then do nothing and continue on. Which way is better? try: A[\"blah\"] = B[\"blah\"] except KeyError: pass or if \"blah\" in B: A[\"blah\"] = B[\"blah\"] \"Do and ask for forgiveness\" vs. \"simplicity and explicitness\". Which is better and why? 回答1: Exceptions are not conditionals

python format string unused named arguments [duplicate]

筅森魡賤 提交于 2019-11-26 09:25:32
问题 This question already has an answer here: partial string formatting 16 answers Let\'s say I have: action = \'{bond}, {james} {bond}\'.format(bond=\'bond\', james=\'james\') this wil output: \'bond, james bond\' Next we have: action = \'{bond}, {james} {bond}\'.format(bond=\'bond\') this will output: KeyError: \'james\' Is there some workaround to prevent this error to happen, something like: if keyrror: ignore, leave it alone (but do parse others) compare format string with available named

Checking a nested dictionary using a dot notation string “a.b.c.d.e”, automatically create missing levels

半世苍凉 提交于 2019-11-26 08:32:13
问题 This one is blowing my mind. Given the following dictionary: d = {\"a\":{\"b\":{\"c\":\"winning!\"}}} I have this string (from an external source, and I can\'t change this metaphor). k = \"a.b.c\" I need to determine if the dictionary has the key \'c\', so I can add it if it doesn\'t. This works swimmingly for retrieving a dot notation value: reduce(dict.get, key.split(\".\"), d) but I can\'t figure out how to \'reduce\' a has_key check or anything like that. My ultimate problem is this:

Nested defaultdict of defaultdict

末鹿安然 提交于 2019-11-25 23:54:27
问题 Is there a way to make a defaultdict also be the default for the defaultdict? (i.e. infinite-level recursive defaultdict?) I want to be able to do: x = defaultdict(...stuff...) x[0][1][0] {} So, I can do x = defaultdict(defaultdict) , but that\'s only a second level: x[0] {} x[0][0] KeyError: 0 There are recipes that can do this. But can it be done simply just using the normal defaultdict arguments? Note this is asking how to do an infinite-level recursive defaultdict, so it\'s distinct to

How does collections.defaultdict work?

浪子不回头ぞ 提交于 2019-11-25 23:50:29
问题 I\'ve read the examples in python docs, but still can\'t figure out what this method means. Can somebody help? Here are two examples from the python docs >>> from collections import defaultdict >>> s = \'mississippi\' >>> d = defaultdict(int) >>> for k in s: ... d[k] += 1 ... >>> d.items() [(\'i\', 4), (\'p\', 2), (\'s\', 4), (\'m\', 1)] and >>> s = [(\'yellow\', 1), (\'blue\', 2), (\'yellow\', 3), (\'blue\', 4), (\'red\', 1)] >>> d = defaultdict(list) >>> for k, v in s: ... d[k].append(v) ..