[英]Why do I get an error but it still shows the correct output , does anyone I have a fix?
[英]Does anyone know why i do not get an output, the code does compile but returns no output
employees =[
{
"name": "John Doe",
"job": "Software Engineer",
"City": "Vancouver",
"age": 34,
"status": "single"
},
{
"name": "Alicia Smith",
"job": "Director",
"City": "New York",
"age": 38,
"status": "Married"
}
]
keys = ["name", "age"]
if "name" and "age" in employees:
newDict = employees.pop("name" and "age")
print(newDict)
您的代碼中有一些錯誤。 我相信您正試圖從字典中刪除鍵name
和age
。 請嘗試以下操作:
employees = [
{
"name": "John Doe",
"job": "Software Engineer",
"City": "Vancouver",
"age": 34,
"status": "single"
},
{
"name": "Alicia Smith",
"job": "Director",
"City": "New York",
"age": 38,
"status": "Married"
}
]
newDict = []
for d in employees: # First iterate over the dictionaries
if "name" in d: # If the key "name" is there in the dictionary
d.pop("name") # Remove it
if "age" in d: # Check if "age" is there in the keys
d.pop("age") # Remove it too if present
newDict.append(d) # Add the updated dictionary to our list
print(newDict)
首先,您在代碼中遇到了兩個錯誤,第一個是因為 if 語句不正確,這就是未執行的原因。 第二,你不能在數組中彈出一個字典,你必須選擇每個,然后彈出它們或像這個解決方案一樣將它們放入循環中
employees =[ { "name": "John Doe", "job": "Software Engineer", "City": "Vancouver", "age": 34, "status": "single" }, { "name": "Alicia Smith", "job": "Director", "City": "New York", "age": 38, "status": "Married" } ]
newDict = []
for i in employees:
if "name" and "age" in i:
i.pop("name" and "age")
newDict.append(i)
print(newDict)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.