本文目錄一覽:
- 1、python中如何將字符串轉換為字典
- 2、每日一課 | Python拆分字符串後轉成字典
- 3、Python : 怎麼把字符串轉換成字典(key : value)的形式
- 4、Python中如何將格式化字符串轉換成字典
python中如何將字符串轉換為字典
python中,經常遇到字符串需要轉換成字典的情況,那麼,如何將字符串轉化成字典呢?方法如下:
使用 literal_eval
導包ast
每日一課 | Python拆分字符串後轉成字典
很少有Python示例向您展示如何將字符串拆分為字典。
結果:
結果:
結果:
希望本文的內容對大家的學習或者工作能帶來一定的幫助,每天進步一點點,加油
Python : 怎麼把字符串轉換成字典(key : value)的形式
a = “{‘a’ : ‘hi’, ‘b’ : ‘hello’}”
b = eval(a)
b
{‘a’ : ‘hi’, ‘b’ : ‘hello’}
這樣轉換,即把每一行獲取到作為一個字符串,eval即可
Python中如何將格式化字符串轉換成字典
#-*-coding:utf-8-*-
#1、字典
dict = {‘name’: ‘Zara’, ‘age’: 7, ‘class’: ‘First’}
#字典轉為字符串,返回:type ‘str’ {‘age’: 7, ‘name’: ‘Zara’, ‘class’: ‘First’}
print type(str(dict)), str(dict)
#字典可以轉為元組,返回:(‘age’, ‘name’, ‘class’)
print tuple(dict)
#字典可以轉為元組,返回:(7, ‘Zara’, ‘First’)
print tuple(dict.values())
#字典轉為列表,返回:[‘age’, ‘name’, ‘class’]
print list(dict)
#字典轉為列表
print dict.values
#2、元組
tup=(1, 2, 3, 4, 5)
#元組轉為字符串,返回:(1, 2, 3, 4, 5)
print tup.__str__()
#元組轉為列表,返回:[1, 2, 3, 4, 5]
print list(tup)
#元組不可以轉為字典
#3、列表
nums=[1, 3, 5, 7, 8, 13, 20];
#列錶轉為字符串,返回:[1, 3, 5, 7, 8, 13, 20]
print str(nums)
#列錶轉為元組,返回:(1, 3, 5, 7, 8, 13, 20)
print tuple(nums)
#列表不可以轉為字典
#4、字符串
#字符串轉為元組,返回:(1, 2, 3)
print tuple(eval(“(1,2,3)”))
#字符串轉為列表,返回:[1, 2, 3]
print list(eval(“(1,2,3)”))
#字符串轉為字典,返回:type ‘dict’
print type(eval(“{‘name’:’ljq’, ‘age’:24}”))
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/190949.html