Python 将字典类型的参数转换为字符串参数

将字典类型的参数按照 ASCII 码排序并拼接成字符串,其中键和值之间用等号连接,不同的键值对之间用指定连接符连接。

from collections import OrderedDict


# 按照ASCII码排序并拼接
def sort_ascii(connector, params):
    params = OrderedDict(sorted(params.items()))
    result = ""
    for key, value in params.items():
        result += f'{connector}{key}={value if value else ""}'
    if result.find(connector) == 0:
        result = result[1:]
    return result


if __name__ == "__main__":
    params = {"name": "rtf", "mobile": "18112345678", "gender": "male"}
    print(f"sort_ascii&:{sort_ascii('&', params)}")
    print(f"sort_ascii|:{sort_ascii('|', params)}")

你可能感兴趣的:(Python,python)