如何附加到字典词典 [英] How to append to a dictionary of dictionaries

查看:50
本文介绍了如何附加到字典词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建这样的词典字典:

I'm trying to create a dictionary of dictionaries like this:

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

但是我正在从SQL表中填充它.因此,我已将SQL表拉入一个名为结果"的SQL对象.然后我得到了这样的列名:

But I am populating it from an SQL table. So I've pulled the SQL table into an SQL object called "result". And then I got the column names like this:

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

该表具有大约40个特征,因此很长.

The table has about 40 characteristics, so it is quite long.

我可以做到...

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

但是,这当然看起来很可怕,并且需要花费一些时间来编写.而且我仍在研究如何构建整个产品,因此可能需要对它进行几次更改……这可能会变得非常乏味.

But this of course would look horrible and take a while to write. And I'm still working out how I want to build this whole thing so it's possible I'll need to change it a few times...which could get extremely tedious.

有干的方法吗?

推荐答案

假定第0列是您希望用作键的内容,并且您确实希望构建字典字典,然后创建字典:

Assuming that column 0 is what you wish to use as your key, and you do wish to build a dictionary of dictionaries, then its:

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

概括,如果列 k 是您的身份,则其为:

Generalising, if column k is your identity then its:

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

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

(Here each sub dictionary is all columns other than column k)

这篇关于如何附加到字典词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆