Anubhav Singh Anubhav Singh - 11 days ago 5
Python Question

How to append ' at end of values in python dictionary

import json

body = { u'username': u"aws", u'status': u'Full', u'lname': u'Singh',u'company_id': {u'displayName': u'Root'},u'person_no': u'89',u'fname': u'Aws', u'gender':2, u'userid': u'guest'}
data = json.dumps(body)
json_data = loads(data)

keylist = data.keys()


I have extracted the primary keys(tier 1 keys) : primary_keylist i.e

[u'username', u'status', u'person_no', u'gender', u'company_id', u'lname', u'fname', u'userid']


Now I want to append ' to all values corresponding to tier 1 keys.

I tried:

json_data[key] = json_data[key] + "'"


If I am using it to change single value, then it is working
but when I am trying to update all key(in primary_keylist)

for key in keylist:
if key in primary_keylist:
json_data[key] = json_data[key] + "'"
else:
pass


then it is not working.
How to update all the values at once?

Error: TypeError: unsupported operand type(s) for +: 'dict' and 'str'

Answer

Try the following:

primary_keylist = [u'username',u'status',u'person_no',u'gender', u'company_id', u'lname', u'fname', u'userid']

res = [key+"'" for key in keys]

Output::

>>>res
[u"username'", u"status'", u"person_no'", u"gender'", u"company_id'", u"lname'", u"fname'", u"userid'"]

To update values in json_data, use the following:

res = {item[0]:str(item[1])+"'" for item in json_data.items()}

Output:

>>> import json
>>>
>>> body = { u'username': u"aws", u'status': u'Full', u'lname': u'Singh',u'company_id': {u'displayName': u'Root'},u'person_no': u'89',u'fname': u'Aws', u'gender':2, u'userid': u'guest'}
>>> res = {item[0]:str(item[1])+"'" for item in body.items()}
>>> res
{u'username': "aws'", u'status': "Full'", u'person_no': "89'", u'gender': "2'", u'userid': "guest'", u'company_id': "{u'displayName': u'Root'}'", u'lname': "Singh'", u'fname': "Aws'"}
Comments