Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = 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 lose the original order. So I tried to do it with an OrderedDict, but I cannot get it to work. This 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 OrderedDict objects based on the fruit keys.

like image 211
user3609179 Avatar asked Feb 23 '17 00:02

user3609179


People also ask

How does Defaultdict work if you try to read from a Defaultdict?

A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.

Is Defaultdict faster than dict?

Finally, using a defaultdict to handle missing keys can be faster than using dict.

Does Defaultdict maintain order?

DefaultDict ,on append elements, maintain keys sorted in the order of addition [duplicate]

How does Defaultdict work Defaultdict stores a copy of a dictionary?

Defaultdict is a sub-class of the dictionary class that returns a dictionary-like object. The functionality of both dictionaries and defaultdict are almost same except for the fact that defaultdict never raises a KeyError. It provides a default value for the key that does not exists.


Video Answer


1 Answers

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
like image 57
Raymond Hettinger Avatar answered Sep 23 '22 01:09

Raymond Hettinger