Questions tagged [dictionary-missing]

Used to mark questions relating the Python magic method called when a dictionary key is missing.

From the dict documentation: "If a subclass of dict defines a method __missing__() and key is not present, the d[key] operation calls that method with the key key as argument. The d[key] operation then returns or raises whatever is returned or raised by the __missing__(key) call. No other operations or methods invoke __missing__()."

7 questions
65
votes
7 answers

How to make a dictionary that returns key for keys missing from the dictionary instead of raising KeyError?

I want to create a python dictionary that returns me the key value for the keys are missing from the dictionary. Usage example: dic = smart_dict() dic['a'] = 'one a' print(dic['a']) # >>> one a print(dic['b']) # >>> b
sorin
  • 161,544
  • 178
  • 535
  • 806
9
votes
5 answers

A forgiving dictionary

I am wondering how to create forgiving dictionary (one that returns a default value if a KeyError is raised). In the following code example I would get a KeyError; for example a = {'one':1,'two':2} print a['three'] In order not to get one I would…
James
  • 605
  • 1
  • 5
  • 9
6
votes
3 answers

functools.wrapper - AttributeError: attribute '__doc__' of 'type' objects is not writable

While executing the code below, I'm getting AttributeError: attribute '__doc__' of 'type' objects is not writable. from functools import wraps def memoize(f): """ Memoization decorator for functions taking one or more arguments. Saves…
user2264738
  • 302
  • 4
  • 18
6
votes
1 answer

Python 2 __missing__ method

I wrote a very simple program to subclass a dictionary. I wanted to try the __missing__ method in python. After some research i found out that in Python 2 it's available in defaultdict. ( In python 3 we use collections.UserDict though..) The…
SeasonalShot
  • 2,357
  • 3
  • 31
  • 49
5
votes
1 answer

How to extend OrderedDict with defaultdict behavior

I have a list of OrderedDict objects. I would like to combine all of them together and then sort them by the fruit attribute in each of them. I have been trying to combine and sort them using defaultdict using the code below: super_dict_apple =…
1
vote
4 answers

Python: How to assign a function to an Object attribute?

Basically this started with my problem that I had when trying to find if the index exist in a dict: if collection[ key ]: # if exist #do this else: # if no exist #do this But when the index really doesn't exist it throws me a KeyError. So,…
A. K. Tolentino
  • 2,112
  • 3
  • 25
  • 33
0
votes
1 answer

insertdict_clean: Assertion error

I get the following error in python 2.6.6: python: Objects/dictobject.c:501: insertdict_clean: Assertion 'ep->me_value == ((void *)0)' failed. Following is the distilled source: pool = multiprocessing.Pool(32) mutation_counts = pool.map(mutate,…
kporter
  • 2,684
  • 17
  • 26