gpt4 book ai didi

python - 从嵌套字典中删除键(Python 键)

转载 作者:行者123 更新时间:2023-11-28 21:32:09 24 4
gpt4 key购买 nike

我对 Python 还很陌生,提前感谢您的帮助。

我构建了以下代码(我尝试了下面的代码,我在字典中使用了字典)。

这个想法是保留键(hair.color)和值(blonde)。在此示例中:删除 Micheal。

代码:

def answers(hair_questions):
try:
for i in people:
if people[i]["hair.color"]==hair_questions:
print(people[i])
else:
del people[i]
return people[i]
except:
print("Doesn´t exist")

answers("brown")

关于人:

people={
"Anne":
{
"gender":"female",
"skin.color":"white",
"hair.color":"blonde",
"hair.shape":"curly"
}
,
"Michael":
{

"citizenship":"africa",
"gender":"male",
"hair.color":"brown",
"hair.shape":"curly"


}
,

"Ashley":
{
"gender":"female",
"citizenship":"american",
"hair.color":"blonde",
"hair.shape":"curly "
}

}

代码仅检查第一个键:条件为:values(blonde)(people[i]["hair.color"]!=brown)它只适用于 1 个键,然后代码就会“卡住”

我当前的输出:

"people"=

"Michael":
{

"citizenship":"africa",
"gender":"male",
"hair.color":"brown",
"hair.shape":"curly"


}
,

"Ashley":
{
"gender":"female",
"citizenship":"american",
"hair.color":"blonde",
"hair.shape":"curly "
}

相反,我想要:

"people"=

"Michael":
{

"citizenship":"africa",
"gender":"male",
"hair.color":"brown",
"hair.shape":"curly"

}

在本例中,我想要一个输出(仅)Michael。

最佳答案

迭代 for 循环时无法删除键:

people={
"Anne":
{
"gender":"female",
"skin.color":"white",
"hair.color":"blonde",
"hair.shape":"curly"
},
"Michael":
{
"citizenship":"africa",
"gender":"male",
"hair.color":"brown",
"hair.shape":"curly"
},
"Ashley":
{
"gender":"female",
"citizenship":"american",
"hair.color":"blonde",
"hair.shape":"curly "
}
}

def answers(hair_questions):
my_dict = {}
for i in people:
if people[i]["hair.color"] in hair_questions:
my_dict[i] = people[i]
return my_dict

print(answers("brown"))

def answers(hair_questions):
my_list = []
for i in people:
if people[i]["hair.color"] not in hair_questions:
my_list.append(i)

for i in my_list:
del people[i]

answers("brown")
print(people)

操作:

{'Michael': {'citizenship': 'africa', 'gender': 'male', 'hair.color': 'brown', 'hair.shape': 'curly'}}

关于python - 从嵌套字典中删除键(Python 键),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56950943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com