Search code examples
pythonjsondictionary-comprehension

Add a prefix to each key in Json dictionary list using comprehension


I am looking to add a prefix to each key in a JSON so my message looks as follows, with tmp. prefix

[{'tmp.p.class': 'B', 'tmp.timestamp': '2020-08-07 09:00:00'}, {'tmp.p.class': 'A', 'tmp.timestamp': '2020-08-07 09:00:05'}]

import json      
x = [{'p.class': 'B', 'timestamp': '2020-08-07 09:00:00'}, {'p.class': 'A', 'timestamp': '2020-08-07 09:00:05'}]
data = json.dumps(x)

y = [{'tmp.'+k: v for k, v in d.items()} for d in data]
print(y)

Traceback (most recent call last): File "./prog.py", line 5, in File "./prog.py", line 5, in AttributeError: 'str' object has no attribute 'items'


Solution

  • you don't need to serialize the python object to a string. You can directly perform the modification on the list x.

    y = [{"tmp." + k: v for k, v in d.items()} for d in x]