我正在生成字典词典,有时候每个键可能会有一组以上的词典。
#ds and point are lists of dictionaries
def pointList(ds, point, filepath):
startTime = datetime.now()
dictPoint = {}
for ik in ds:
if ik['ItemK'] in dictPoint:
print ("This item key (%s) is already in dict point." % ik['ItemK'])
# add {'MasterKey' : ik['MasterKey'], 'PointId' : None}
# to the dictPoint like below
# Now make the dictionary at dictPoint[str(ik['ItemK'])]
# keep the previous entry that exists
dictPoint[str(ik['ItemK'])] = {'MasterKey' : ik['MasterKey'], 'PointId' : None}
for sk in point:
dictPoint[str(sk['PointK'])]['PointId'] = sk['PointId']
因此,如果我当前的字典试图添加一个带有PointK = 24
的元素和一个字典
{..., '24': {'MasterKey': '126', 'PointId': None}, ... }
已经存在,我该如何制作这样的字典
{..., '24': {'MasterKey': ['126','132'], 'PointId': [None,None]}, ... }
解决方法(有点) 所以这个解决方案只有在只有一个副本的情况下才有效,如果有超过2个相同的ItemK则它不会工作我相信
d = {'MasterKey' : [dictPoint[str(ik['ItemK'])]['MasterKey'],ik['MasterKey']],
'PointId' : [None, None] }
dictPoint[str(ik['ItemK'])] = d
无论如何,当字典中已经为这两个元素组成了列表时,这项工作是否正常工作?
答案 0 :(得分:0)
试试这个:
for ik in ds:
dictPoint.setdefault(ik['ItemK'], {}).setdefault('MasterKey', []).append(ik['MasterKey'])
dictPoint.setdefault(ik['ItemK'], {}).setdefault('PointId', []).append(ik['PointId'])
唯一的缺点是MasterKey和PointId将永远是列表,即使只有一个