How to extend OrderedDict with defaultdict behavior
Asked Answered
K

1

5

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.

Kellerman answered 23/2, 2017 at 0:12 Comment(4)
How does it not work. You should always be able to describe that in detail.Ridotto
Please show an example of what you're getting and another example of what you expect.Jae
Likely, it doesn't work because an OrderedDict is not a defaultdict so it doesn't automatically set a default value when accessing. If only there were dict method that setdefault...DOTDOTRidotto
Mention input, output you are getting and expected output.Electroencephalograph
C
10

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
Chi answered 23/2, 2017 at 0:30 Comment(2)
'TypeError: 'type' object has no attribute 'getitem''Kellerman
You've got an error elsewhere in your code. Perhaps you left off the parentheses off when instantiating the dictionaries. It should be super_dict_apple = OrderedDictWithDefaultList() instead of super_dict_apple = OrderedDictWithDefaultList.Chi

© 2022 - 2024 — McMap. All rights reserved.