Python – 构造由分隔符分隔的字典键值对
给定一个由 delim 分隔的键值对的字符串,构造一个字典。
Input : test_str = ‘gfg#3, is#9, best#10’, delim = ‘#’
Output : {‘gfg’: ‘3’, ‘is’: ‘9’, ‘best’: ’10’}
Explanation : gfg paired with 3, as separated with # delim.
Input : test_str = ‘gfg.10’, delim = ‘.’
Output : {‘gfg’: ’10’}
Explanation : gfg paired with 10, as separated with . delim.
方法 #1:使用 split() + 循环
在此,我们对逗号执行拆分以获取键值对,并再次对自定义 delim 进行拆分以分离键值对。然后使用循环分配给字典。
Python3
# Python3 code to demonstrate working of
# Contruct dictionary Key-Value pairs separated by delim
# Using split() + loop
# initializing strings
test_str = 'gfg$3, is$9, best$10'
# printing original string
print("The original string is : " + str(test_str))
# initializing delim
delim = "$"
# split by comma for getting different dict values
dicts = test_str.split(', ')
res = dict()
for sub in dicts:
# 2nd split for forming Key-Values for dictionary
res[sub.split(delim)[0]] = sub.split(delim)[1]
# printing result
print("The constructed dictionary : " + str(res))
Python3
# Python3 code to demonstrate working of
# Contruct dictionary Key-Value pairs separated by delim
# Using split() + dictionary comprehension
# initializing strings
test_str = 'gfg$3, is$9, best$10'
# printing original string
print("The original string is : " + str(test_str))
# initializing delim
delim = "$"
# split by comma for getting different dict values
dicts = test_str.split(', ')
# dictionary comprehension to form dictionary
res = {sub.split(delim)[0] : sub.split(delim)[1] for sub in dicts}
# printing result
print("The constructed dictionary : " + str(res))
输出
The original string is : gfg$3, is$9, best$10
The constructed dictionary : {'gfg': '3', 'is': '9', 'best': '10'}
方法 #2:使用字典理解 + split()
与上述方法类似,不同之处在于字典理解用于执行字典构建任务。
Python3
# Python3 code to demonstrate working of
# Contruct dictionary Key-Value pairs separated by delim
# Using split() + dictionary comprehension
# initializing strings
test_str = 'gfg$3, is$9, best$10'
# printing original string
print("The original string is : " + str(test_str))
# initializing delim
delim = "$"
# split by comma for getting different dict values
dicts = test_str.split(', ')
# dictionary comprehension to form dictionary
res = {sub.split(delim)[0] : sub.split(delim)[1] for sub in dicts}
# printing result
print("The constructed dictionary : " + str(res))
输出
The original string is : gfg$3, is$9, best$10
The constructed dictionary : {'gfg': '3', 'is': '9', 'best': '10'}