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

时间:2019-07-09 10:52:09

标签: python string dictionary

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

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

这个想法是将键(hair.color)保留为values(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。

2 个答案:

答案 0 :(得分:3)

迭代循环时不能删除密钥:

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"))

OR

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)

O / P:

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

答案 1 :(得分:2)

您可以使用列表理解:

brown = {key:value for key,value in people.items() if people[key]["hair.color"] != "blonde"}
print (brown)

等于:

brown= {}
for key,value in people.items():
    if people[key]["hair.color"] != "blonde":
        brown[key] = value
print (brown)

输出:

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