pythontip 字符串转为字典

编写一个程序将字符串转换为字典。

定义函数convert_str_list_to_dict(),参数为str_list(输入的字符串)。
在函数内部,创建一个字典,其中每个字符串使用=进行分割,第一部分为键,第二部分为值。
返回字典。

  • 先用字符串转列表,for s in list1:a,b=s.split('=')转为两个值
点击查看代码
def convert_str_list_to_dict(str_list):
    # 此处编写代码 
    list1 = str_list.split()
    dic = {}
    for s in list1:
        a, b = s.split('=')
        dic[a] = b
    return dic
# 输入字符串 
str_list = input()

# 调用函数 
print(convert_str_list_to_dict(str_list))

posted @ 2025-11-10 21:38  硫酸钡barit  阅读(8)  评论(0)    收藏  举报