如何在Python中隔离字典数据

2024-09-23 20:24:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了不同部门不同付款的数据库:

paymentType={"Cash":0,"Amex":0,"All Other Cards":0}
departments={"Lounge":0,"MBar":0,"Resto":0,"TBar":0,"TFloor":0,"Events":0}
for dep in departments.keys():
    data=paymentType
    departments[dep]=data

但是,当我将值赋给特定部门中的“paymentType”之一时

departments["Lounge"]["Cash"]=8

它改变了所有“部门”的“现金”价值

我想保留通过字符串赋值的能力,这就是为什么我不使用类的原因


Tags: 数据库datacashall部门cardsotherdepartments
2条回答

经理不仅要查字典,而且每次都要编一本新字典

departments={"Lounge":0,"MBar":0,"Resto":0,"TBar":0,"TFloor":0,"Events":0}
for dep in departments.keys():

    departments[dep]={"Cash":0,"Amex":0,"All Other Cards":0}
` ``

你需要使用

data=paymentType.copy()

否则,将同一字典分配给所有字段

相关问题 更多 >