如何在python中为基于非整数的索引构建2D查找

2024-06-02 09:40:03 发布

您现在位置:Python中文网/ 问答频道 /正文

仍在学习python的基础知识,并一直在搜索类似的示例,但找不到解决方案,因此我的问题是:

我将从IoT服务获取以下数据作为大型JSON对象的一部分:

for structure in IoT.response['where']:
    for where in IoT.response['where'][structure]['wheres']:
        print structure + ' '+ where['where_id'] + ' ' + where['name']

输出:

structure                            location_id                          name
==================================================================================    
df6db2b0-36ac-11e3-b974-1231390b5549 00000000-0000-0000-0000-000100000001 Basement
df6db2b0-36ac-11e3-b974-1231390b5549 58eafc6e-8eab-4452-b48a-3a6f7f1004f7 Bathroom
df6db2b0-36ac-11e3-b974-1231390b5549 00000000-0000-0000-0000-00010000000d Bedroom
df6db2b0-36ac-11e3-b974-1231390b5549 00000000-0000-0000-0000-000100000003 Den
df6db2b0-36ac-11e3-b974-1231390b5549 00000000-0000-0000-0000-000100000010 Dining Room
df6db2b0-36ac-11e3-b974-1231390b5549 00000000-0000-0000-0000-000100000006 Downstairs
df6db2b0-36ac-11e3-b974-1231390b5549 00000000-0000-0000-0000-000100000000 Entryway
df6db2b0-36ac-11e3-b974-1231390b5549 00000000-0000-0000-0000-00010000000b Family Room

问题:

How do I create a simple lookup where I can lookup the name of a location based on the none numeric structure_id and location_id to retrieve the name?

我尝试过对ID进行哈希处理,以便使用数字索引:

location[hash(structure)][hash(where['where_id'])] = where['name']

但是我得到一个列表索引错误:

list index out of range

我确信我在这里遗漏了一些简单或明显的东西


Tags: ofthenameinidforresponselocation
1条回答
网友
1楼 · 发布于 2024-06-02 09:40:03

Mybelocation是一个列表而不是字典。当您询问location[structure]项时,使用默认dict来拥有字典。此外,您不需要使用hash let字典来完成它的工作

import collections
location = collections.defaultdict(dict)
location[structure][where['where_id']] = where['name']

我没有测试过,但应该有用

相关问题 更多 >