SetDefault for nested dictionary in python

How to use setdefault in python for nested dictionary structures. eg..

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

I would like to establish a meaning for them.

+3
source share
2 answers

Assuming what self.tablea dict is, you can use

self.table.setdefault(field,0)

Everything else is similar. Note that if it self.tablealready has a key field, the value associated with this key is returned. Only if there is no key field, is it 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 tracking the score, maybe just take the length of the list:

print(len(foo.CompleteAnalysis['A']['value']))
# 2
+2
source

, . , . , . Oracle XE, Python 3.5 (64 ) pyobbc.

import pyodbc

spam = {}

sqlQuery = ' \
    SELECT actionexecutedon, screenid, eventtype \
    FROM bmx_production_history \
'

connection= pyodbc.connect('dsn=XE;uid=hr;pwd=hr')

try:
        cursor = connection.cursor()
        cursor.execute(sqlQuery)
        records = cursor.fetchall()
        for record in records:

                spam.setdefault(record.SCREENID, {})

                spam[record.SCREENID].setdefault(record.EVENTTYPE, {})

                spam[record.SCREENID][record.EVENTTYPE].setdefault(record.ACTIONEXECUTEDON.strftime('%Y-%m-%d'), 0)
                spam[record.SCREENID][record.EVENTTYPE][record.ACTIONEXECUTEDON.strftime('%Y-%m-%d')]+=1

        print(spam)

finally:
        connection.close()

n.b. Oracle, - GROUP , - - ( ) , , . .

0

Source: https://habr.com/ru/post/1756614/


All Articles