python字符串与字典转换

经常会遇到字典样式字符串的处理,这里做一下记录。


load

load针对的是文件,即将文件内的json内容转换为dict

import json
test_json = json.load(open("test.json"), "r")

loads

loads是直接将字符串对象转换为了dict

import json
test = '{"a":123, "b":456}'
test_json = json.loads(test)



eval

(用eval有时候可能会出现问题,推荐使用loads)

test = '{"a":123, "b":456}'
test_dict = eval(test)

原文地址:https://www.cnblogs.com/NFii/p/11983939.html

时间: 2024-08-04 09:21:52

python字符串与字典转换的相关文章

python字符串列表字典相互转换

字符串转换成字典 json越来越流行,通过python获取到json格式的字符串后,可以通过eval函数转换成dict格式: >>> a='{"name":"yct","age":10}' >>> eval(a) {'age': 10, 'name': 'yct'} 支持字符串和数字,其余格式的好像不支持: 字符串转换成列表和元组 使用list >>>a='1234' >>>

python字符串、字典操作,文件读写

一.字符串操作:name = 'aabc,dddd,a'name1 = 'q '# print(name[3]) #字符串也可以取下标# print(name.capitalize()) #把字符串首字母大写# print(name.center(11,'*')) #把name放中间,字符串少于11,则用*补全# #print(name.index('p')) #返回字符串的索引,查不到时会报错,substring not found# print(name.isalnum()) #只能有数字或

Python字符串和字典相关操作

字符串操作: 字符串的 % 格式化操作: str = "Hello,%s.%s enough for ya ?" values = ('world','hot') print str % values 输出结果: Hello,world.hot enough for ya ? 模板字符串: #coding=utf-8 from string import Template ## 单个变量替换 s1 = Template('$x, glorious $x!') print s1.subs

Python 字符串、列表转换

1.字符转化为字典 例如: name="alex,erric" name_list=name.split(',') print name_list ['alex','erric'] 2.列表转化为字符串 name_list=['alex','eric','tony'] name=','.join.(name_list) print name 'alex,eric,tony'

Python 字符串和list转换

因为python的read和write方法的操作对象都是string.而操作二进制的时候会把string转换成list进行解析,解析后重新写入文件的时候,还得转换成string. >>> import string >>> str = 'abcde' >>> list = list(str) >>> list ['a', 'b', 'c', 'd', 'e'] >>> str 'abcde' >>>

Python 字符串类型列表转换成真正列表类型

我们在写代码的过程中,会经常使用到for循环,去循环列表,那么如果我们拿到一个类型为str的列表,对它进行for循环,结果看下面的代码和图: str_list = str(['a','b','c']) for row in str_list: print(row) 结果: 那么for循环就把str类型的列表的每一个字符都一个一个的循环的打印出来,而这个结果并不是我们想要的,那么如何解决这个问题?,使用到第三方模块,看下面的代码 from ast import literal_eval # 假设拿

python:字符串与二进制转换

msg = "北京"print(msg.encode(encoding = "utf-8"))#字符串转换为二进制数据(参数最好加上utf-8,若没有该参数,则为系统默认的参数,可能不是utf-8编码)print(msg.encode(encoding = "utf-8").decode(encoding = "utf-8"))#二进制数据转换为字符串(参数最好加上utf-8,若没有该参数,则为系统默认的参数,可能不是utf-

python 列表与字典转换

一.列表转字典: 方法1: list_1 = ['abc', 'efg'] list_2 = [123, 456] new_dict = dict(zip(list_1, list_2)) 方法2: list_1 = ['a', 1] list_2 = ['b', 2] list_3 = [list_1, list_2] new_dict = dict(list_3) 二.字典转列表: dict_1 = {'a', 1} list_keys = list(dict_1) list_values

python 字符串 类型互相转换 str bytes 字符串连接

直接看例子: n = 888 print bytes(n)+str1 print str(n)+str1 print type(n) n = bytes(n) print type(n) n = str(n) print type(n) 查看结果 8881234567 8881234567 <type 'int'> <type 'str'> <type 'str'> 原文地址:http://blog.51cto.com/weiruoyu/2334578