从列表中删除字典而不提及键的有效方法

时间:2019-02-04 07:31:02

标签: python-3.x list dictionary

如果字典中的任何一个值为空,从字典列表中删除字典的有效方法是什么?

input = [{'mac': '', 'location': '801'}, 
         {'mac': 'E464EECBA5EB', 'location': '816'}, 
         {'mac': '', 'location': '817'}, 
         {'mac': 'DCE83F3BC820', 'location': '818'}, 
         {'mac': 'GH12TY674RF1', 'location': ''}, 
         {'mac': 'DCE83F3BC820', 'location': '820'}]


expected_output = [{'mac': 'E464EECBA5EB', 'location': '816'},
                   {'mac': 'DCE83F3BC820', 'location': '818'}, 
                   {'mac': 'DCE83F3BC820', 'location': '820'}]

1 个答案:

答案 0 :(得分:4)

您可以使用列表理解:

$sql = "INSERT INTO student (lname, fname, mname, gmail, grade, track, section, status)
VALUES ('$lname', '$fname', '$mname','$email', '$grade', '$strand', '$section', '$status')";
$result = mysqli_query($conn, $sql);
$_SESSION['studentId'] = mysqli_insert_id($conn); //add this line to store the studentId into the session.

$sql = "INSERT INTO student (userID) VALUES ('$last_id')"; // change this line to the one below.

$sql = "UPDATE student SET userID = '$last_id' WHERE studentID = $_SESSION['studentId']";

输出:

input_list = [{'mac': '', 'location': '801'}, 
              {'mac': 'E464EECBA5EB', 'location': '816'}, 
              {'mac': '', 'location': '817'}, 
              {'mac': 'DCE83F3BC820', 'location': '818'}, 
              {'mac': 'GH12TY674RF1', 'location': ''}, 
              {'mac': 'DCE83F3BC820', 'location': '820'}]


expected_output = [d for d in input_list if all(d.values())]