Type Error: Format Requires Mapping

前端 未结 2 785
自闭症患者
自闭症患者 2021-01-01 12:27

I have a string and a list of objects:

gpl = \"%(id)s : %(atr)s\"

objects = [{\'id\':1, \'content\':[{\'atr\':\'big\', \'no\':2}]},  {\'id\':2, \'content\':         


        
2条回答
  •  死守一世寂寞
    2021-01-01 13:17

    You need to turn obj and con into one dictionary - your current code passes in a tuple.

    If you don't care what happens to objects afterwards, use dict.update:

    for obj in objects:
        for con in obj["content"]:
            con.update(obj)
            print gpl % con
    
    1 : big
    2 : small
    

    If you don't want objects modified, you'll need to build an intermediate dictionary:

    for obj in objects:
        for con in obj["content"]:
            print gpl % {'id': obj["id"], 'atr': con["atr"]}
    
    1 : big
    2 : small
    

提交回复
热议问题