首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何访问嵌套字典结构的值

如何访问嵌套字典结构的值
EN

Stack Overflow用户
提问于 2022-04-26 13:43:19
回答 2查看 43关注 0票数 -1

我有一个嵌套的字典结构,我想遍历它,并在嵌套键中打印每个键的值。例如:

代码语言:javascript
复制
    animals = {
        "Bear": {"food": "fish", "claws": "12"},
        "Tiger": {"food": "meat", "claws": "8"},
        "Elephant": {"food": "grass", "claws": "0"},
        "Chicken": {"food": "feed", "claws": "talons"},
        "Wolf": {"food": "rabbits", "claws": "6"}

    }

target_animal = "Tiger"
tfood = ?
tclaws = ?
print("A tiger's food: "+ tfood)
print("A tiger's claws: "+ tclaws)

我已经试过反复

代码语言:javascript
复制
if inner dictionary name == target_animal: 
    for i in kingdom.keys():
        #print(i)
        for j in kingdom[i]:
            innerDict = (kingdom[i][j])

我不知道在哪里检查:是否内部字典名称=“老虎”,也不知道如何只访问目标内部字典中的值。

其目标是遍历“动物”字典,如果键==为target_animal,则打印其内部字典值。

EN

回答 2

Stack Overflow用户

发布于 2022-04-26 13:47:55

你只需把括号锁上:

代码语言:javascript
复制
animals = {
        "Bear": {"food": "fish", "claws": "12"},
        "Tiger": {"food": "meat", "claws": "8"},
        "Elephant": {"food": "grass", "claws": "0"},
        "Chicken": {"food": "feed", "claws": "talons"},
        "Wolf": {"food": "rabbits", "claws": "6"}

}

target_animal = "Tiger"
tfood = animals[target_animal]["food"]
tclaws = animals[target_animal]["claws"]

在上面的代码中,您有相当于animals[target_animal]{"food": "meat", "claws": "8"}。这本身就是一个字典,因此您可以添加["food"]["claws"]来访问值whitin。

票数 1
EN

Stack Overflow用户

发布于 2022-04-26 13:56:52

代码语言:javascript
复制
animals = {
        "Bear": {"food": "fish", "claws": "12"},
        "Tiger": {"food": "meat", "claws": "8"},
        "Elephant": {"food": "grass", "claws": "0"},
        "Chicken": {"food": "feed", "claws": "talons"},
        "Wolf": {"food": "rabbits", "claws": "6"}

    }
# if you just wanna query for one animal, then
target_animal = "Tiger"
target_dict = animals['Tiger'] 
#dtype of target_dict again is a dict, so you can #again use indexing
tfood = target_dict['food']
tclaws = target_dict['claws']
print("A tiger's food: "+ tfood)
print("A tiger's claws: "+ tclaws)

如果你想迭代每一件事

代码语言:javascript
复制
for animal, props in animals.items():
    print(f"A {animal}'s food: {props['food']}")
    print(f"A {animal}'s claws: {props['claws']}")

如果您想使用迭代,但仍然只对老虎过滤,那么

代码语言:javascript
复制
for animal, props in animals.items():
    if animal=='Tiger':
        print(f"A {animal}'s food: {props['food']}")
        print(f"A {animal}'s claws: {props['claws']}")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72015048

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档