简体   繁体   English

如何在Python字典的值末尾附加'

[英]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 ie 我已经提取了主键(第1层键):primary_keylist即

[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. 现在,我想将'附加到与第1层密钥相对应的所有值。

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) 如果我使用它来更改单个值,则它正在工作,但是当我尝试更新所有键时(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'

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: 要更新json_data值,请使用以下命令:

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'"}

To take into account nested dictionaries, use the following: 要考虑嵌套字典,请使用以下命令:

res = {}

for item in body.items():
    if not isinstance(item[1], dict):
        res[item[0]] = str(item[1])+"'"
    else:
        res[item[0]] = {i:str(item[1][i])+"'" for i in item[1]}

Output: 输出:

>>> res
{u'username': "aws'", u'status': "Full'", u'person_no': "89'", u'gender': "2'", u'userid': "guest'", u'company_id': {u'displayName': "Root'"}, u'lname': "Singh'", u'fname': "Aws'"}

Another way to do this: 另一种方法是:

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

primary_keylist = [('').join([item, "'"]) for item in primary_keylist]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM