按键在不同的词典上拆分词典,并指定唯一的名称

2024-05-15 20:48:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典是这样的:

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

但这不是我想要的。 任何想法都将不胜感激。在


Tags: inputagereturn字典statusstephandictmax
3条回答

您可以编写一个小函数来创建新的独立dict,如下所示:

def func(dct):
   names = ('jack', 'stephan', 'anna', 'max')
   return [{k: dct[k].copy()} for k in names]

a, b, c, d = func(dct)
print(a)
# {'jack': {'status': 'single', 'age': 35}}

如果要使用嵌套在主dict中的相同dict,则不需要copy。在

将词典修改为:

d = {'jack': {'age':35, 'status': 'single'}, #seems more intuitive
'stephan': {'age':27, 'status': 'married'},
'anna': {'age':29, 'status': 'married'},
'max': {'age':37, 'status': 'single'}}
#print
a={}
b={}
a['jack']=d['jack']
...
# Transform the dict into a list of dicts
people = [{k: v} for k, v in original_dict.iteritems()]
# Unpack the first 4 elements of the list into 4 new variables
a, b, c, e = people[:4]

相关问题 更多 >