Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setDefault for Nested dictionary in python

How do I use setdefault in python for nested dictionary structures. eg..

self.table[field] = 0
self.table[date] = []
self.table[value] = {}

I would like to setdefault for these.

like image 721
Jayanth Avatar asked Nov 15 '22 08:11

Jayanth


1 Answers

Assuming self.table is a dict, you could use

self.table.setdefault(field,0)

The rest are all similar. Note that if self.table already has a key field, then the value associated with that key is returned. Only if there is no key field is self.table[field] set to 0.

Edit: Perhaps this is closer to what you want:

import collections
class Foo(object):
    def __init__(self):
        self.CompleteAnalysis=collections.defaultdict(
            lambda: collections.defaultdict(list))

    def getFilledFields(self,sentence):
        field, field_value, field_date = sentence.split('|')
        field_value = field_value.strip('\n')
        field_date = field_date.strip('\n')
        self.CompleteAnalysis[field]['date'].append(field_date)
        self.CompleteAnalysis[field]['value'].append(field_value) 

foo=Foo()
foo.getFilledFields('A|1|2000-1-1')
foo.getFilledFields('A|2|2000-1-2')
print(foo.CompleteAnalysis['A']['date'])
# ['2000-1-1', '2000-1-2']

print(foo.CompleteAnalysis['A']['value'])
# ['1', '2']

Instead of keeping track of the count, perhaps just take the length of the list:

print(len(foo.CompleteAnalysis['A']['value']))
# 2
like image 199
unutbu Avatar answered Dec 15 '22 01:12

unutbu