我有 2 个 SQL 表:
CREATE TABLE IF NOT EXISTS `test` (
`id_block` int(11) NOT NULL AUTO_INCREMENT,
`label` varchar(30) NOT NULL,
PRIMARY KEY (`id_block`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=12 ;
INSERT INTO `test` (`id_block`, `label`) VALUES
(1, 'Cat1'),
(2, 'Cat2'),
(3, 'Cat3'),
(4, 'Cat4'),
(5, 'Cat5'),
(6, 'Cat6'),
(7, 'Cat7');
CREATE TABLE IF NOT EXISTS `test2` (
`id_block` int(11) NOT NULL,
`id_parent` int(11) NOT NULL,
PRIMARY KEY (`id_block`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `test2` (`id_block`, `id_parent`) VALUES
(1, 0),
(2, 0),
(3, 2),
(4, 2),
(5, 3),
(6, 4),
(7, 2);
一个块可能有一个、两个或三个父级,这就是我有 2 个表的原因。
这是我的 SQL 查询:
SELECT T.id_block, T2.id_block, label, id_parent
FROM test T
INNER JOIN test2 T2 ON T.id_block = T2.id_block
我使用此脚本将这些信息放入列表中:
conn = MySQLdb.connect('localhost','user','pass', 'db')
curs = conn.cursor()
result=curs.execute("SELECT ....")
cats = curs.fetchall()
curs.close()
conn.close()
输出 :
cats = ((1L, 1L, 'Cat1', 0L), (2L, 2L, 'Cat2', 0L), (3L, 3L, 'Cat3', 2L), (4L, 4L, 'Cat4', 2L), (5L, 5L, 'Cat5', 3L), (6L, 6L, 'Cat6', 4L), (7L, 7L, 'Cat7', 2L))
我想要一个像这样的分层/嵌套字典:
dict = {"Cat1": {}, "Cat2": {"Cat3": {"Cat5": {}}, "Cat4": {}, "Cat7": {}}}
你有什么解决办法吗?
提前致谢,