如何附加到字典词典

时间:2017-04-28 03:09:55

标签: python dictionary

我试图创建一个像这样的字典词典:

food = {"Broccoli": {"Taste": "Bad", "Smell": "Bad"},
        "Strawberry": {"Taste": "Good", "Smell": "Good"}}

但是我从SQL表中填充它。所以我把SQL表拉到了一个名为" result"的SQL对象中。然后我得到了这样的列名:

nutCol = [i[0] for i in result.description]

该表有大约40个特征,所以它很长。

我可以这样做......

foodList = {}
for id, food in enumerate(result):
    addMe = {str(food[1]): {nutCol[id + 2]: food[2], nulCol[idx + 3]: 
            food[3] ...}}
    foodList.update(addMe)

但这当然看起来很糟糕,需要一段时间才能写出来。而且我还在研究如何构建这一整体,以便我可能需要更改它几次......这可能会非常繁琐。

有干嘛的方法吗?

3 个答案:

答案 0 :(得分:2)

为了使解决方案位置无关,您可以使用dict1.update(dict2)。这简单地将dict2与dict1合并。

在我们的情况下,因为我们有dict的词典,我们可以使用dict['key']作为dict1,只需添加任何其他键值对作为dict2。

这是一个例子。

food = {"Broccoli": {"Taste": "Bad", "Smell": "Bad"}, 
        "Strawberry": {"Taste": "Good", "Smell": "Good"}}

addthis = {'foo':'bar'}

假设您要将addthis dict添加到food['strawberry'],我们可以简单地使用,

food["Strawberry"].update(addthis)

获得结果:

>>> food
{'Strawberry': {'Taste': 'Good', 'foo': 'bar', 'Smell': 'Good'},'Broccoli': {'Taste': 'Bad', 'Smell': 'Bad'}}
>>>  

答案 1 :(得分:1)

addMe = {str(food[1]):dict(zip(nutCol[2:],food[2:]))}

zip将获取两个(或更多)项目列表并将元素配对,然后您可以将结果传递给dict以将这些对转换为字典。

答案 2 :(得分:1)

假设第0列是您希望用作密钥的,并且您确实希望构建字典字典,那么:

detail_names = [col[0] for col in result.description[1:]]
foodList = {row[0]: dict(zip(detail_names, row[1:]))
            for row in result}

概括,如果列k是您的身份,那么:

foodList = {row[k]: {col[0]: row[i]
                     for i, col in enumerate(result.description) if i != k}
            for row in result}

(此处每个子词典都是列k以外的所有列)

相关问题