簡體   English   中英

如果值有空列表,則從字典列表中刪除字典

[英]Remove dictionary from list of dictionaries if value has empty list

我有一個字典列表,字典中有一個列表。

{
   "Credentials": [
      {
         "realName": "Mark Toga",
         "toolsOut": [
            "TL-482940",
            "TL-482940"
         ],
         "username": "291F"
      },
      {
         "realName": "Burt Mader",
         "toolsOut": [],
         "username": "R114"
      },
      {
         "realName": "Tim Johnson",
         "toolsOut": [
            "TL-482940"
         ],
         "username": "E188"
      }
   ]
}

我正在嘗試解析此文件,以便它顯示如下內容:

馬克·托加:TL-482940、TL482940 蒂姆·約翰遜:TL-482940

忽略 Burt Mader,因為他沒有工具。

我已經達到了它顯示上述內容的地步,Burt Mader 仍然 ( GUI output )

編輯:這是 newstr6 的打印輸出而不是 GUI 圖像。 我確實想要我的應用程序的 GUI,但為了便於閱讀:

Mark Toga: 'TL-482940', 'TL-482940',
 Burt Mader: ,
 Tim Johnson: 'TL-482940'

這是我當前的代碼(我確信有很多效率改進,但我主要關心用空列表省略字典。)

## importing libraries
import json
from tkinter import *
from tkinter import ttk
from functools import partial
import pprint

mainWin = Tk()
mainWin.geometry('400x480')
mainWin.title('Select Tooling')

with open('Inventory.json','r+') as json_file:
    data=json.load(json_file)
    credData = data['Credentials']
    noSID = [{k: v for k, v in d.items() if k != 'username'} for d in credData]

    print(noSID)

    pp = pprint.pformat(noSID)
    ps = str(pp)

    newstr1 = ps.replace('[','')
    newstr2 = newstr1.replace(']','')
    newstr3 = newstr2.replace('{','')
    newstr4 = newstr3.replace('}','')
    newstr5 = newstr4.replace("'realName': '","")
    newstr6 = newstr5.replace("', 'toolsOut'","")

    text = Label(mainWin,text=newstr6)
    text.pack()

quitButton = Button(mainWin,text="Log Out",command=lambda:mainWin.destroy())
quitButton.pack()

mainWin.mainloop()

只需通過應用特定條件來過濾您的詞典列表。 在這種情況下,字典鍵toolsOut關聯的內容應該被斷言為True

def process_data(list_of_dicts, field):
    res = []
    for item in list_of_dicts:
        if item[field]:
            res.append(item)
    return res

credData = process_data(data["Credentials"], "toolsOut")

這聞起來像一個XY 問題 您不想顯示沒有檢出工具的人,但實際上不需要將他們從列表中刪除來執行此操作。 您依靠pprint將字典轉換為字符串,然后弄亂該字符串。 相反,只需從頭開始構建字符串,不要包括沒有檢查工具的人。

data=json.load(json_file)
credData = data['Credentials']

# Since you're the one creating the string, you can choose what you want to put in it
# No need to create a NEW dictionary without the username keys
outstr = ""
for person in credData:
    outstr += person['realName'] + ": " + ", ".join(person['toolsOut']) + "\n"

print(outstr)

這打印:

Mark Toga: TL-482940, TL-482940
Burt Mader: 
Tim Johnson: TL-482940

現在,既然您想忽略那些沒有任何工具的人,請添加該條件。

outstr = ""
for person in credData:
    if person['toolsOut']:
        outstr += person['realName'] + ": " + ", ".join(person['toolsOut']) + "\n"

print(outstr)

你得到:

Mark Toga: TL-482940,TL-482940
Tim Johnson: TL-482940

if person['toolsOut']if len(person['toolsOut']) == 0相同,因為空列表是Falsy

如果您真的想刪除credData中具有空toolsOut鍵的元素,您可以在列表理解中使用相同的條件。

credData2 = [person for person in credData if person['toolsOut'])

加載“憑據”列表時,您可以過濾掉不需要的項目:

credData  = [d for d in data['Credentials'] if d.get("toolsOut")]

或者您可以為過濾后的憑據設置一個單獨的變量

credWithTools = [d for d in credData if d.get("toolsOut")]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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