dictionary-missing

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

試著忘記壹切 提交于 2019-12-17 07:26:44
问题 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 回答1: dict s have a __missing__ hook for this: class smart_dict(dict): def __missing__(self, key): return key 回答2: Why don't you just use dic.get('b', 'b') Sure, you can subclass dict as others point out, but I find it handy to remind myself every once in a while that get can

How to extend OrderedDict with defaultdict behavior

こ雲淡風輕ζ 提交于 2019-12-13 15:05:07
问题 I have a list of orderdicts. And I would like to combine all of them together and then sort them by the fruit attribute in each of them. I have been to combine and sort them using defaultdict through the code below. super_dict_apple = defaultdict(list) super_dict_orange = defaultdict(list) super_dict_no_fruit = defaultdict(list) for d in dict: if 'fruit' not in d: for k, v in d.iteritems(): super_dict_no_fruit[k].append(v) elif d['fruit'] == 'Apple': for k, v in d.iteritems(): super_dict

Python 2 __missing__ method

时间秒杀一切 提交于 2019-12-11 13:14:52
问题 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 __getitem__ is the on responsible for calling the __missing__ method if the key isn't found. When i implement __getitem__ in the following program i get a key error, but when i implement without it, i get the desired value. import collections class

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

江枫思渺然 提交于 2019-11-27 04:34:54
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 dict s have a __missing__ hook for this: class smart_dict(dict): def __missing__(self, key): return key Daren Thomas Why don't you just use dic.get('b', 'b') Sure, you can subclass dict as others point out, but I find it handy to remind myself every once in a while that get can have a default value! If you want to have a go at the defaultdict , try this: dic = defaultdict() dic._