Home > front end >  Does anyone know why i do not get an output, the code does compile but returns no output
Does anyone know why i do not get an output, the code does compile but returns no output

Time:11-12

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)

CodePudding user response:

There are a few mistakes in your code. I believe that you're trying to remove the keys name and age from the dictionaries wherever present. Try the following:

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)

CodePudding user response:

You can use a dict comprehension inside a list comprehension for a one-liner.

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

If you want to perform it in multiple lines, you should make a copy of the dictionary before removing items from it. Otherwise, you would get the following error.

RuntimeError: dictionary changed size during iteration

CodePudding user response:

first you got two errors in the code the first one because the if statement is not correct that is why is not being executed. second you can't pop a dict inside array you got to choose each one and then pop them or put them in loop like this solution

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)


        
  • Related