如何在 dict 内,根据指定的 value,查找出想要的 key 和 value

2022-02-08 11:12:20 +08:00
 css3

请教一下,python内给定以下dict, 已知"Huber"= "Tucker", 求"Huber"= "Tucker"所在dict内的data_id及其在"Armstrong"内的索引

{
    "Armstrong": [
        {
            "date_id": "1",
            "show_name": "Quynn",
            "description": "Quynn",
            "commid": "Ward",
            "Mooney": {
                "Carpenter": "Bolton",
                "Amena": "Elijah",
                "Rice": {
                    "Kitra": false,
                    "Huber": "Shafira",
                    "novalidate": "Valdez0"                    
                }
            },
            "Graham": "Mariko",
            "status": {
                "status": "OFF",
            },
            "Alyssa": {
                "Little": "Noelani",
                "device_id": "Sparks",
            },
            "Judah": "Huff"
        },
        {
            "date_id": "2",
            "show_name": "Holland",
            "description": "Holland",
            "commid": "Spencer",
            "Mooney": {
                "Carpenter": "Illana",
                "Amena": "Rosa",
                "Rice": {
                    "Kitra": false,
                    "Huber": "Tucker",
                    "novalidate": "Evelyn"                    
                }
            },
            "Graham": "Janna",
            "status": {
                "status": "ON",
            },
            "Alyssa": {
                "Little": "Drew",
                "device_id": "Herman",
            },
            "Judah": "England"
        }
        # ....很多
    ],
    "page": {
        "offset": 0,
        "limit": 100,
        "total": 2
    }
}
3577 次点击
所在节点    Python
10 条回复
wannaspring
2022-02-08 11:26:47 +08:00
def fun (targetv, dicts):
if isinstance(dicts, dict):
for key,value in d.items():
if value == targetv:
return key
if isinstance(value, dict):
fun(targetv, value)
if isinstance(dicts, list):
wannaspring
2022-02-08 11:27:45 +08:00
不是很熟悉 python ,但是这样是不是可以?,剩下的 list 自己补一下
NessajCN
2022-02-08 11:56:41 +08:00
for r in dict["Armstrong"]:
if r["Mooney"]["Rice"]["Huber"]=="Tucker":
print r["date_id"]
print dict["Armstrong"].index(r)
ykk
2022-02-08 13:43:17 +08:00
字典是 O(n) 遍历就完了,已知某些规律可以缩小遍历空间
seven123
2022-02-08 14:08:39 +08:00
遍历就完了
julyclyde
2022-02-08 15:49:06 +08:00
这是不是传说中的“倒排索引”?
wsgfz000
2022-02-08 16:17:17 +08:00
试试 bidict
Latin
2022-02-08 17:36:10 +08:00
SenLief
2022-02-08 18:41:43 +08:00
这不是遍历吗
wellsc
2022-02-08 18:57:40 +08:00
倒排索引

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/832393

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX