Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Error: Format Requires Mapping

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': [{'atr':'small', 'no':3}]}]

for obj in objects:
   for con in obj['content']:
       print gpl %(obj,con)

I get:

TypeError: format requires a mapping

How would I print this? I am trying to print:

1 : big
2 : small

Thank you

like image 499
Neeran Avatar asked Apr 03 '12 09:04

Neeran


2 Answers

Since your formatting string uses named parameters:

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

You need to provide keys (the names) in a dictionary as an argument to reference back to named formatting keys in the formatting string:

print gpl % {'id': obj['id'], 'atr': con['atr']}

So your code would be:

for obj in objects:
    for con in obj['content']:
        print gpl% {'id': obj['id'], 'atr': con['atr']}
like image 159
Preet Kukreti Avatar answered Nov 09 '22 08:11

Preet Kukreti


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
like image 35
Wieland Avatar answered Nov 09 '22 08:11

Wieland