Python – 将字符串列表转换为键值列表字典
给定一个字符串,将其转换为键值列表字典,其中键为第一个单词,其余单词为值列表。
Input : test_list = [“gfg is best for geeks”, “CS is best subject”]
Output : {‘gfg’: [‘is’, ‘best’, ‘for’, ‘geeks’], ‘CS’: [‘is’, ‘best’, ‘subject’]}
Explanation : 1st elements are paired with respective rest of words as list.
Input : test_list = [“gfg is best for geeks”]
Output : {‘gfg’: [‘is’, ‘best’, ‘for’, ‘geeks’]}
Explanation : 1st elements are paired with respective rest of words as list.
方法 #1:使用 split() + 循环
在此,我们对每个字符串进行迭代,然后使用 split() 对字符串进行拆分,将第一个元素指定为键并将其他元素打包到列表中,使用 *运算符并创建键值列表对。
Python3
# Python3 code to demonstrate working of
# Convert String List to Key-Value List dictionary
# Using split() + loop
# initializing list
test_list = ["gfg is best for geeks", "I love gfg", "CS is best subject"]
# printing string
print("The original list : " + str(test_list))
res = dict()
for sub in test_list:
# split() for key
# packing value list
key, *val = sub.split()
res[key] = val
# printing results
print("The key values List dictionary : " + str(res))
Python3
# Python3 code to demonstrate working of
# Convert String List to Key-Value List dictionary
# Using split() + dictionary comprehension
# initializing list
test_list = ["gfg is best for geeks", "I love gfg", "CS is best subject"]
# printing string
print("The original list : " + str(test_list))
# using dictionary comprehension to solve this problem
res = {sub[0] : sub[1:] for sub in (ele.split() for ele in test_list)}
# printing results
print("The key values List dictionary : " + str(res))
输出
The original list : ['gfg is best for geeks', 'I love gfg', 'CS is best subject']
The key values List dictionary : {'gfg': ['is', 'best', 'for', 'geeks'], 'I': ['love', 'gfg'], 'CS': ['is', 'best', 'subject']}
方法#2:使用 split() + 字典理解
这是解决此问题的类似方法。在这里,字典理解被用来解决这个问题。
Python3
# Python3 code to demonstrate working of
# Convert String List to Key-Value List dictionary
# Using split() + dictionary comprehension
# initializing list
test_list = ["gfg is best for geeks", "I love gfg", "CS is best subject"]
# printing string
print("The original list : " + str(test_list))
# using dictionary comprehension to solve this problem
res = {sub[0] : sub[1:] for sub in (ele.split() for ele in test_list)}
# printing results
print("The key values List dictionary : " + str(res))
输出
The original list : ['gfg is best for geeks', 'I love gfg', 'CS is best subject']
The key values List dictionary : {'gfg': ['is', 'best', 'for', 'geeks'], 'I': ['love', 'gfg'], 'CS': ['is', 'best', 'subject']}