将字符串转换为字典的方法
字典是Python中的一个无序集合,它存储数据值,如地图,即key:value
对。为了将字符串转换为字典,存储的字符串必须采用可以从中生成key:value
对的方式。本文演示了将字符串转换为字典的几种方法。
方法一:拆分字符串生成字典的key:value
对
在这种方法中,将分析给定的字符串,并使用split()
方法将字符串拆分为生成key:value
对以创建字典。
下面是该方法的实现。
# Python implementation of converting
# a string into a dictionary
# initialising string
str = " Jan = January; Feb = February; Mar = March"
# At first the string will be splitted
# at the occurence of ';' to divide items
# for the dictionaryand then again splitting
# will be done at occurence of '=' which
# generates key:value pair for each item
dictionary = dict(subString.split("=") for subString in str.split(";"))
# printing the generated dictionary
print(dictionary)
输出:
{' Feb ': ' February', ' Mar ': ' March', ' Jan ': ' January'}
方法2:使用2个字符串为字典生成key:value
对
在这种方法中,将考虑 2 个不同的字符串,其中一个将用于生成键,另一个将用于为字典生成值。操作两个字符串后,将使用这些key:value
对创建字典项。
下面是该方法的实现。
# Python implementation of converting
# a string into a dictionary
# initialising first string
str1 = "Jan, Feb, March"
str2 = "January | February | March"
# splitting first string
# in order to get keys
keys = str1.split(", ")
# splitting second string
# in order to get values
values = str2.split("|")
# declaring the dictionary
dictionary = {}
# Assigning keys and its
# corresponding values in
# the dictionary
for i in range(len(keys)):
dictionary[keys[i]] = values[i]
# printing the generated dictionary
print(dictionary)
输出:
{'Jan': 'January ', 'Feb': ' February ', 'March': ' March'}
方法 3:使用zip()
方法组合从 2 个字符串中提取的key:value
对
在这种方法中,将再次使用 2 个字符串,一个用于生成键,另一个用于为字典生成值。当所有的键和值都存储后, zip()
方法将用于创建key:value
对,从而生成完整的字典。
下面是该方法的实现。
# Python implementation of converting
# a string into a dictionary
# initialising first string
str1 = "Jan, Feb, March"
str2 = "January | February | March"
# splitting first string
# in order to get keys
keys = str1.split(", ")
# splitting second string
# in order to get values
values = str2.split("|")
# declaring the dictionary
dictionary = {}
# Merging all keys and values
# to generate items for
# the dictionary
dictionary = dict(zip(keys, values))
# printing the generated dictionary
print(dictionary)
输出:
{' March': ' March', 'Jan': 'January ', ' Feb': ' February '}
方法四:如果字符串本身就是字符串字典的形式
在这种方法中,使用ast.literal_eval()
方法将已经是字符串,即具有字典字符串的字符串转换为字典。
下面是该方法的实现。
# Python implementation of converting
# a string into a dictionary
# importing ast module
import ast
# initialising string dictionary
str = '{"Jan" : "January", "Feb" : "February", "Mar" : "March"}'
# converting string into dictionary
dictionary = ast.literal_eval(str)
# printing the generated dictionary
print(dictionary)
输出:
{'Feb': 'February', 'Jan': 'January', 'Mar': 'March'}