通过键在单独的词典上拆分字典并分配唯一的名称

时间:2017-08-28 11:46:37

标签: python python-3.x dictionary

我的字典看起来像这样:

d = {'jack': {'age':35, 'status': 'single'}, 
'stephan': {'age':27, 'status': 'married'},
'anna': {'age':29, 'status': 'married'},
'max': {'age':37, 'status': 'single'}}

我最终的目标是通过一个键将它分成4个单独的词典,并用以下唯一名称命名每个词典:

a = {'jack': {'age':35, 'status': 'single'}}
b = {'stephan': {'age':27, 'status': 'married'}}
c = {'anna': {'age':29, 'status': 'married'}}
e = {'max': {'age':37, 'status': 'single'}}

我有一个按键拆分字典并返回字典列表的函数:

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

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

3 个答案:

答案 0 :(得分:1)

将字典修改为:

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']
...

答案 1 :(得分:1)

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

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中的相同dicts,那么你不需要copy

答案 2 :(得分:0)

// list of existing accounts
List<Account> accounts = new ArrayList<>(transactionObj.getAccounts());

foreach(Account account : accounts){
    account.setId(null);
}

transactionObj.setAccounts(accounts);

// just persist transactionObj using EntityManager merge() method.