我有一个字典列表,字典里有一个列表
{
"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 still(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()
加载“凭证”列表时,您可以过滤掉不需要的项目:
或者,您可以为筛选的凭据使用单独的变量
只需应用特定条件筛选字典列表。在这种情况下,dict key
toolsOut
关联的内容应断言为True
:这闻起来像X-Y Problem。您不希望显示未签出工具的人员,但实际上不需要将其从列表中删除即可。您依赖
pprint
将字典转换为字符串,然后再处理该字符串。相反,只需从头开始构建字符串,并且不包括未签出工具的人员这张照片是:
现在,由于您想忽略没有任何工具的人员,请添加该条件
你会得到:
if person['toolsOut']
与if len(person['toolsOut']) == 0
相同,因为空列表是Falsy如果确实要删除
credData
中具有空toolsOut
键的元素,可以在列表理解中使用相同的条件相关问题 更多 >
编程相关推荐