python - 从嵌套字典中删除键(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。
解决方案
迭代 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'}}
推荐阅读
- r - 在多核上使用 Igraph
- azure - O365 基于组的许可不起作用
- svg - 如何从带有材质 ui 的 SVG 图像创建 SVG 图标?
- javascript - 如何使用javascript打开剑道角度日期选择器弹出窗口
- php - 使用自动生成的 DATETIME 和默认值 CURRENT_TIMESTAMP 插入新对象的 symfony 4 教义错误
- python - 解析电子邮件以识别关键字
- javascript - Django中可修改的项目符号列表
- python - 如何使用 Python 在浏览器中打开网站?
- c# - 使用 LINQ、GroupBy 更改输出样式
- extjs - Sencha ExtJs5 一个模型和一个视图中的多个模型