簡體   English   中英

有誰知道為什么我沒有得到輸出,代碼確實編譯但不返回任何輸出

[英]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)

您的代碼中有一些錯誤。 我相信您正試圖從字典中刪除鍵nameage 請嘗試以下操作:

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)

您可以在單行列表理解中使用字典理解

print([{k: v for k, v in d.items() if k not in keys} for d in employees])

如果您想在多行中執行它,您應該在從中刪除項目之前制作字典的副本。 否則,您將收到以下錯誤。

RuntimeError: dictionary changed size during iteration

首先,您在代碼中遇到了兩個錯誤,第一個是因為 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM