【问题标题】:Does anyone know why i do not get an output, the code does compile but returns no output有谁知道为什么我没有得到输出,代码编译但没有返回输出
【发布时间】:2021-12-24 11:11:26
【问题描述】:
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)

【问题讨论】:

  • 请格式化您的代码。
  • 请给出您的预期输出
  • 您的 if 语句没有按照您的想法执行。它目前正在做(姓名)和(员工年龄)
  • 解释你正在尝试做什么以及你想要什么输出是一般的好习惯。如果您还没有,请查看描述 how to ask a question 的链接。

标签: python list set


【解决方案1】:

您可以在list comprehension 中使用dict comprehension 来实现单行。

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

如果您想在多行中执行它,您应该在从中删除项目之前制作字典的副本。否则会出现以下错误。

RuntimeError: dictionary changed size during iteration

【讨论】:

    【解决方案2】:

    您的代码中有一些错误。我相信您正在尝试从字典中删除键 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)
    

    【讨论】:

      【解决方案3】:

      首先你在代码中有两个错误,第一个是因为 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)
      
      
              
      

      【讨论】:

      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多