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_apple[k].append(v)
        elif d['fruit'] == 'orange':
            for k, v in d.iteritems():
                super_dict_orange[k].append(v)  

With this I get one key and all the associated values, but I loose the original order. So I tried to do it with an orderDict, but I cannot get it to work, below is what I tried.

from collections import OrderedDict

order_dict_no_fruit = OrderedDict()
order_dict_apple = OrderedDict()
order_dict_orange = OrderedDict()

for d in dict:
        if 'fruit' not in d:
            for k, v in d.iteritems():
                order_dict_no_fruit[k].append(v)
        elif d['fruit'] == 'Apple':
            for k, v in d.iteritems():
                order_dict_apple[k].append(v)
        elif d['fruit'] == 'orange':
            for k, v in d.iteritems():
                order_dict_orange[k].append(v) 

My main goal is to keep the original order of the dictionaries but combine them into three different orderDicts based on the fruit keys.


回答1:


Instead of a regular OrderedDict, try a subclass that adds in defaultdict behavior:

class OrderedDictWithDefaultList(OrderedDict):
    def __missing__(self, key):
        value = list()
        self[key] = value
        return value


来源:https://stackoverflow.com/questions/42404728/how-to-extend-ordereddict-with-defaultdict-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!