1

我有 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": {}}}

你有什么解决办法吗?

提前致谢,

4

1 回答 1

0

这里有一个解决方案:

#! /usr/bin/python
# -*- coding: utf-8 -*-
# Python v2.7  
############################################################################# 
def _creadict(c, d={}):

    # recherche des enfants
    for cle in d:
        for cat, catpar in c:
            if catpar==cle:
                d[cle][cat] = {}
        # recherche récursive
        d[cle] = _creadict(c, d[cle])        

    return d  
#============================================================================ 
def creadict(cats):

    # simplification de la liste => [[cat, catparent], ...]
    c = []
    for i, (id1, id2, cat, idpar) in enumerate(cats):
        if idpar==0:
            c.append([cat, 0])
        else:
            for elem in cats:
                if idpar==elem[0]:
                    c.append([cat, elem[2]])
                    break    

    # recherche des 'cat' sans parent (catpar==0)
    d = {}
    for cat, catpar in c:
        if catpar==0:
            d[cat] = {}

    # recherche récursive des enfants
    d = _creadict(c, d)

    return d  
cats = ((1, 1, 'Cat1', 0), (2, 2, 'Cat2', 0), (3, 3, 'Cat3', 2), (4, 4, 'Cat4', 2), (5, 5, 'Cat5', 3), (6, 6, 'Cat6', 4), (7, 7, 'Cat7', 2))
d = creadict(cats)
print d
于 2013-04-09T09:52:13.813 回答