Python - 根据值的大小限制拆分字典值
给定一个包含字符串值的字典,任务是编写一个Python程序来在字符串的大小超过 K 时拆分值。
Input : {1 : “Geeksforgeeks”, 2 : “best for”, 3 : “all geeks”}, limit = 5
Output : {1: ‘Geeks’, 2: ‘forge’, 3: ‘eks’, 4: ‘best ‘, 5: ‘for’, 6: ‘all g’, 7: ‘eeks’}
Explanation : All string values are capped till length 5. New value is created post size limit.
Input : {1 : “Geeksforgeeks”, 2 : “best for”}, limit = 5
Output : {1: ‘Geeks’, 2: ‘forge’, 3: ‘eks’, 4: ‘best ‘, 5: ‘for’}
Explanation : All string values are capped till length 5. New value is created post size limit.
方法:使用字典理解+ enumerate() +列表切片
在这里,我们使用列表切片和列表理解来执行获取所需值块的任务,这些值是使用 values() 提取的值的迭代。下一步是使用列表理解和 enumerate() 用新的分块值重新分配键。
Python3
# Python3 code to demonstrate working of
# Split Dictionary values on size limit
# Using dictionary comprehension + enumerate() + list slicing
# initializing dictionary
test_dict = {1: "Geeksforgeeks",
2: "best for", 3:
"all geeks"}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing limit
limit = 4
# cutting chunks of K
chunks = (sub[idx: idx + limit] for sub in test_dict.values()
for idx in range(0, len(sub), limit))
# re assigning dictionary with chunks
res = {key: val for key, val in enumerate(chunks, 1)}
# printing result
print("The extracted values : " + str(res))
输出:
The original dictionary is : {1: ‘Geeksforgeeks’, 2: ‘best for’, 3: ‘all geeks’}
The extracted values : {1: ‘Geek’, 2: ‘sfor’, 3: ‘geek’, 4: ‘s’, 5: ‘best’, 6: ‘ for’, 7: ‘all ‘, 8: ‘geek’, 9: ‘s’}