【问题标题】:How to convert dict to string in concatenation?如何在连接中将dict转换为字符串?
【发布时间】:2020-01-11 02:08:26
【问题描述】:

我有一个由 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 的结果。

我如何得到这个?

【问题讨论】:

    标签: python json dictionary merge


    【解决方案1】:

    看起来您正在获取 dict 值中的列表列表,在这种情况下,您可以展平列表并加入字符串“,”,例如:

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

    【讨论】:

    • 嗨 Sagar,更新了我的整个代码并按照您的建议 url = 'https://propertypro.zendesk.com/api/v2/tickets/update_many.json?' + \ 'ids=' + ','.join(chain.from_iterable(data)) 但它没有成功 4249 <class 'dict'> 4089 <class 'dict'> Status: 400 Problem with the request. Exiting.
    • 请检查您的请求,HTTP 状态400 表示Bad request。检查您的输入 json。
    【解决方案2】:

    如果要将id 的值转换为逗号分隔的字符串,可以执行以下操作。

    ','.join(id.values())
    

    所以把你的代码改成

    url = 'str,' + 'str1:' + ','.join(id.values())
    

    为了完整起见,如果您想对字典键做同样的事情,您只需使用

    ','.join(id)
    

    【讨论】:

    • 嗨 Deepstop,尝试了你的建议 url = 'https://propertypro.zendesk.com/api/v2/tickets/update_many.json?' + 'ids=' + ','.join(id.values()) 但收到此错误 4249 <class 'dict'> 4089 <class 'dict'> Traceback (most recent call last): File "put_comment.py", line 17, in <module> 'ids=' + ','.join(id.values()) TypeError: sequence item 0: expected str instance, list found 我在这里做错了什么?
    • 我没有复制您的原始帖子,现在您更改了我写的内容不再适用。不过,您现在似乎已经知道如何使用joinchain_from_iterables,并且您已经删除了url = 'str,' + 'str1:' + ,因此您提出的问题似乎不再与您修改后的代码相匹配。那么你的问题是什么,你在哪一行得到错误?
    • 嗨,在检查我的代码后,我实际上需要使用循环分配新变量,但它会覆盖值,我只能从最后一次迭代中得到结果,这是我现在的确切问题,如何使用循环将dict分配给新var并将其转换为字符串逗号分隔值?
    • id_merged = [result['id'] for result in data['results'] 将为列表data 的元素的每个字典创建一个包含id 字段值的列表。
    • 嗨,Deepstop,感谢您的帮助!我现在能够获得我想要的价值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    相关资源
    最近更新 更多