首页 > 解决方案 > 从嵌套字典中删除键(Python 键)

问题描述

我是 Python 的新手,在此先感谢您的帮助。

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

这个想法是用值(金发)保留键(hair.color)。在此示例中:删除 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。

标签: pythonstringdictionary

解决方案


迭代 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'}}

推荐阅读