我想制作一个函数,其输入是一个字典,可以从一个 kvpair 到几个。它应该将 kvs 分组为字符串,格式为:
str1 = '[{"name":key1, "v": value1}, {"name":key2,"v":value2},...{"name":key4,"v":4}]'
一个字符串最多应该只有 4 kv 对。如果字典中有更多,那么函数应该构建str2,str3等。 例如,如果有17个kv对,我需要5个字符串(4*4 + 1),最后一个字符串只打印key:value 17 .
如果字典的长度总是 4 个条目,我就是这样做的
keys = list(dict.keys())
values = list(dict.values())
string= '['
for i in range(0, 4):
string = string + ('{"name":"' + str(keys[i]) + '","v":' + str(values[i]) + '}')
if i == 3:
string = string + ']'
break
string = string + ','
但是现在 dict 的长度可变,我不知道如何正确切片,以便仅使用 4 kv 对构建字符串
干得好
from itertools import zip_longest
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(fillvalue=fillvalue, *args)
def dict2str(in_dict, group_size=1):
out_str = []
for dict_group in grouper(group_size, in_dict.items()):
out_str.append('[' + ', '.join([f'{{"name":{kv[0]}, "v":{kv[1]}}}' for kv in dict_group if kv != None]) + ']')
return out_str
# Try out the function
my_dict = {'key1':1,
'key2':2,
'key3':3,
'key4':4,
'key5':5,
'key6':6,
'key7':7,
'key8':8,
'key9':9,
'key10':10,
'key11':11,
'key12':12,
'key13':13,
'key14':14,
'key15':15,
'key16':16,
'key17':17}
my_str = dict2str(my_dict, group_size=4)
这里发生了什么:
{"name":key, "v":value}
。请注意,如果没有更多元素,则grouper
返回None
,因此您必须确保您的键值对不是None
,
用作分隔符以及[
]
开始和结束字符最后你得到你的字符串列表,每个聚类 <=4 个项目(如果group_size=4
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句