- import ast
- import json
-
- # 字符串转字典
- str_of_dict = "{'key1': 'key1value', 'key2': 'key2value'}"
- dict1 = ast.literal_eval(str_of_dict)
- print(type(dict1), dict1)
-
- # 字符串转字典
- str1 = '{"name": "oscar", "age": 18}'
- dict1 = json.loads(str1)
- print(dict1)
- print(type(dict1))
-
- # 字典转字符串
- my_dict = {'key1': 'key1value', 'key2': 'key2value'}
- str1 = str(my_dict)
- print(type(str1), str1)
-
- # 字典转字符串
- d = {"a": 1, "b": 2}
- ds = json.dumps(d)
- print(type(ds), ds)
-
- # eval函数的官方解释为:将字符串str当成有效的表达式来求值并返回计算结果。即通过eval可以把list,tuple,dict和string相互转化,例如:
- a = "[[1,2], [3,4]]"
- b = eval(a)
- print(type(b))
-
- a = "{1: 'a', 2: 'b'}"
- b = eval(a)
- print(type(b))
-
- a = "([1,2], [3,4], [5,6], (9,0))"
- b = eval(a)
- print(type(b))
-
- # dict 与list 转换
- d1 = {
- 'en': '英语',
- 'cn': '中文',
- 'fr': '法语',
- 'jp': '日语'
- }
- list_values = [i for i in d1.values()] # list_values=list(d1.values())
- list_keys = [i for i in d1.keys()] # list_values=list(d1.keys())
-
- print(list_values, list_keys)
-
- d2 = dict(zip(list_keys, list_values)) #使用zip函数转
- print(d2)
-
-
- #字典转列表
- dit = {'a1': 'name1',
- 'a2': 'name2',
- 'a3': 'name3'}
- lst_key = []
- lst_value = []
- for key, value in dit.items():
- lst_key.append(key)
- lst_value.append(value)
- print(lst_key)
- print(lst_value)
运行结果:
{'key1': 'key1value', 'key2': 'key2value'}
{'name': 'oscar', 'age': 18}
{'key1': 'key1value', 'key2': 'key2value'}
{"a": 1, "b": 2}
['英语', '中文', '法语', '日语'] ['en', 'cn', 'fr', 'jp']
{'en': '英语', 'cn': '中文', 'fr': '法语', 'jp': '日语'}
['a1', 'a2', 'a3']
['name1', 'name2', 'name3']