我正在根据 SQLite 查询构建一个字典,该字典根据其前面的键对某个值求和。我想要做的是将 SQLite 查询之外的键值插入从所述查询创建的字典中。
EX:
query_3 = cur.execute('''SELECT upc AS upc,
description AS desc,
department AS dept_no,
substr((datetime),1,4) AS year,
substr((datetime),6,2) AS month,
sum(total) AS spend,
count(distinct(substr((datetime),12,2) || register_no ||
emp_no || trans_no)) as Transactions,
sum(CASE WHEN (trans_status = 'V' or trans_status = 'R') THEN -1 ELSE 1 END) as Items
FROM transactions
WHERE department != 0 and
department != 15 and
trans_status != 'M' and
trans_status != 'C' and
trans_status != 'J' and
(trans_status = '' or
trans_status = ' ' or
trans_status = 'V' or
trans_status = 'R')
GROUP BY desc, year, month''')
d3 = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(int))))))))
for row in cur.fetchall() :
upc, desc, dept_no, year, month, spend, transactions, items = row
d3[upc][desc][dept_no][year][month]['spend'] += spend
d3[upc][desc][dept_no][year][month]['trans'] += transactions
d3[upc][desc][dept_no][year][month]['items'] += items
我想要做的是在dict [dept_name]
中的[dept_no]
键后添加d3
键。我用相应的dept_no / dept_names
创建了一个单独的字典,我只是不知道如何将它们合并到我的字典d3
中。
答案 0 :(得分:0)
如果我理解正确,这样就可以了。
d3[upc][desc][dept_no]['dept_name'] = "Something"
您只需为其指定一个值,即可在现有字典中创建一个键。
示例:强>
mydict = {'something': 1,'something2': 2}
print(mydict)
>>> {'something': 1, 'something2': 2} # print shows 2 values
mydict['something3'] = 3 # add a new key
print(mydict)
>>> {'something': 1, 'something3': 3, 'something2': 2} # now print shows 3 values, which confirms that we added a new key and value to the dict.