我有一本字典是这样的:
d = {'jack': {'age':35, 'status': 'single'},
'stephan': {'age':27, 'status': 'married'},
'anna': {'age':29, 'status': 'married'},
'max': {'age':37, 'status': 'single'}}
我的最终目标是用一个键将其分为4个单独的字典,并为每个字典命名一个唯一的名称,如:
^{pr2}$我有一个函数,它按键拆分dict并返回字典列表:
def split_dict_equally(input_dict, chunks=4):
# prep with empty dicts
return_list = [dict()] * chunks
idx = 0
for k,v in input_dict.items():
return_list[idx][k] = v
if idx < chunks-1: # indexes start at 0
idx += 1
else:
idx = 0
return return_list
但这不是我想要的。 任何想法都将不胜感激。在
您可以编写一个小函数来创建新的独立dict,如下所示:
如果要使用嵌套在主dict中的相同dict,则不需要
copy
。在将词典修改为:
相关问题 更多 >
编程相关推荐