将字典值转换为字符串的Python程序
给定混合数据类型作为值的字典,任务是编写一个Python程序,将不同的 delim 转换为解析的字符串。
例子:
Input : test_dict = {‘Gfg’ : 4, ‘is’ : “1”, ‘best’ : [8, 10], ‘geek’ : (10, 11, 2)}, list_delim, tuple_delim = ‘-‘, ‘^’
Output : {‘Gfg’: ‘4’, ‘is’: ‘1’, ‘best’: ‘8-10’, ‘geek’: ’10^11^2′}
Explanation : List elements are joined by -, tuples by ^ symbol.
Input : test_dict = {‘Gfg’ : 4, ‘is’ : “1”, ‘best’ : [8, 10], ‘geek’ : (10, 11, 2)}, list_delim, tuple_delim = ‘*’, ‘,’
Output : {‘Gfg’: ‘4’, ‘is’: ‘1’, ‘best’: ‘8*10’, ‘geek’: ‘10,11,2’}
Explanation : List elements are joined by *, tuples by , symbol.
示例:使用循环+ isinstance() + join()
在此,我们使用 isinstance() 检查所有值数据类型,并使用 join() 连接以获取差异分隔符,转换为已解析的字符串。
Python3
# Python3 code to demonstrate working of
# Convert dictionary values to Strings
# Using loop + isinstance()
# initializing dictionary
test_dict = {'Gfg' : 4,
'is' : "1",
'best' : [8, 10],
'geek' : (10, 11, 2)}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing delims
list_delim, tuple_delim = '-', '^'
res = dict()
for sub in test_dict:
# checking data types
if isinstance(test_dict[sub], list):
res[sub] = list_delim.join([str(ele) for ele in test_dict[sub]])
elif isinstance(test_dict[sub], tuple):
res[sub] = tuple_delim.join(list([str(ele) for ele in test_dict[sub]]))
else:
res[sub] = str(test_dict[sub])
# printing result
print("The converted dictionary : " + str(res))
输出:
The original dictionary is : {‘Gfg’: 4, ‘is’: ‘1’, ‘best’: [8, 10], ‘geek’: (10, 11, 2)}
The converted dictionary : {‘Gfg’: ‘4’, ‘is’: ‘1’, ‘best’: ‘8-10’, ‘geek’: ’10^11^2′}