python - 如何在连接中将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
。
我怎么得到这个?
解决方案
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'
推荐阅读
- angular - 如何在通过 nginx 反向代理托管的多个应用程序中使用“ng serve”?
- database - 如何创建对 Sage ERP 数据库具有只读访问权限的帐户以与 pyodbc 一起使用
- anylogic - 扩散的低音模型
- r - 如何在 r 中的 Shiny 应用程序中计时反应功能
- python - Python:改变我的结果
- bash - 设置特定的图像亮度
- python - 如何在 python 轮中包含预构建的共享对象库?
- javascript - 如何在 JavaScript 代码中调用 Python 3 函数?
- php - 是否可以更改 hash("ripemd128", $password) 以使用 password_verify($password, $hashed_password)
- ios - 线程 1:致命错误:索引超出范围。没有快速从数组中获取值,控制台显示它们不是空数组