如何追加'在python字典中的值的末尾

时间:2016-11-24 11:55:11

标签: python python-2.7 python-3.x 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()

我已经提取了主键(第1层密钥):primary_keylist即

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

现在我想追加'对应于第1层密钥的所有值。

我试过了:

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

如果我使用它来更改单个值,那么它正在运行 但是当我试图更新所有密钥(在primary_keylist中)时

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

然后它不起作用。 如何一次更新所有值?

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

2 个答案:

答案 0 :(得分:0)

尝试以下方法:

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]

<强>输出:

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

要更新json_data中的值,请使用以下命令:

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

<强>输出:

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

要考虑嵌套词典,请使用以下命令:

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]}

<强>输出:

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

答案 1 :(得分:0)

另一种方法:

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]