首页 > 解决方案 > 如何在连接中将dict转换为字符串?

问题描述

我有从返回以下结果的 API 调用生成的 python 字典类

{'url':' https ://propertypro.zendesk.com/api/v2/tickets/4249.json','id':4249,'external_id':无}

{'url':' https ://propertypro.zendesk.com/api/v2/tickets/4089.json','id':4089,'external_id':无}

代码如下;

from urllib.parse import urlencode

import requests

credentials = 'some email', 'some password'
session = requests.Session()
session.auth = credentials

params = {
    'query': 'type:ticket tags:test_python',
    'sort_order': 'asc'
}

url = 'https://propertypro.zendesk.com/api/v2/search.json?' + urlencode(params)
response = session.get(url)
if response.status_code != 200:
    print('Status:', response.status_code,
          'Problem with the request. Exiting.')
    exit()

# Print the subject of each ticket in the results
data = response.json()

我迭代数据以获取键“id”中的所有值,以将其分配给变量id_merged作为字符串,用逗号分隔

for result in data['results']:
    # Ticket to update
    id_merged = (result['id'])

但只得到一个结果而不是 2,var 在循环中被覆盖?

from test_search import data
import json
import requests

# Iterate the search result
for result in data['results']:
    # Ticket to update
    id_merged = (result['id'])

print("**Start**")
print(id)
body = 'Test ticket'

# Package the data in a dictionary matching the expected JSON
data_comment = {'ticket': {'comment': {'body': body}}}

# Encode the data to create a JSON payload
payload = json.dumps(data_comment)

# Set the request parameters
url = 'https://propertypro.zendesk.com/api/v2/tickets/update_many.json?' + \
    'ids=' + str(id_merged)
user = 'some email'
pwd = 'some password'
headers = {'content-type': 'application/json'}

# Do the HTTP put request
response = requests.put(url, data=payload,
                        auth=(user, pwd), headers=headers)

# Check for HTTP codes other than 200
if response.status_code != 200:
    print('Status:', response.status_code,
          'Problem with the request. Exiting.')
    exit()

# Report success
print('Successfully added comment to ticket #{}'.format(id))

我想得到类似的结果'https://propertypro.zendesk.com/api/v2/tickets/update_many.json?' + \ 'ids=' + 4249,4089

我怎么得到这个?

标签: pythonjsondictionarymerge

解决方案


Looks like you are getting list of list in dict values, in that case you can flatten the list and join on string "," like:

>>> import itertools
>>> ",".join(map(str, list(itertools.chain(*[[1,2,3],[4,5]]))))
'1,2,3,4,5'

推荐阅读