我有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);
一个块可能有一个、两个或三个父级,这就是为什么我有两个表。在
这里是我的SQL查询:
^{pr2}$我用这个脚本将这些信息放入一个列表中:
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": {}}}
你有什么解决办法吗?在
提前谢谢你
这里有一个解决方案:
相关问题 更多 >
编程相关推荐