how to fix TypeError: format requires a mapping

Denis McMahon denismfmcmahon at gmail.com
Wed Jul 1 21:20:09 EDT 2015


On Wed, 01 Jul 2015 14:57:14 -0700, hinaimran.mehr wrote:

> I am pulling my hair with this problem right now,
> 
> I have the following Data structure
> 
>     [<OldSample {u'counter_name': u'cpu_util', u'user_id': u'id',
>     u'resource_id': u'id', u'timestamp': u'2015-06-30T15:53:55',
>     u'counter_volume': 0.043}]

This isn't a print out of any python data structure that I recognise. I 
assume you have a list of dictionaries, and that each dictionary 
represents one sample.

> I need to make it something like this to put in EON pubnub charting
> libaray (see link: http://www.pubnub.com/developers/eon/chart/spline/)
> 
>     message: {
>           columns: [
>             ["y": 0.043, "x": "2015-06-30T15:53:55"],
>             ["y": 0.045, "x": "2015-06-30T15:53:55"]
>           ]
> 
> Now I have the following code
> 
>     data = cclient.samples.list(meter_name ='cpu_util', limit=2)
> 
> result_rows = []
> for row in data:
>      formatted = """["y": %(counter_volume)0.3f, "x":
>      "%(timestamp)s"]""" % (row)
>      result_rows.append(formatted)
>      
>      print(',\n'.join(result_rows))
> 
> 
> clean_json(data)

I assume you want the output as json.

The solution may be to put the data into a suitable structure and dump 
the structure to json.

import json

thing = {}
msg = {}
cols = []

for row in data:
    col = {}
    col['x'] = row['timestamp']
    col['y'] = row['counter_volume']
    cols.append(col)

msg['columns'] = cols

thing['message'] = msg

print thing

print json.dumps(thing)


-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list