根据键值拆分字典



我有一本字典,看起来像这样:

dict = {
"name 1": "abc..",
"location 1": "abc..",
"name 2": "abc..",
"location 2": "abc"
.
.
}

我的目标是将其拆分为n个子字典(取决于第一个字典中整数的范围(,以获得如下结果:

#output
output_dict = {
"dict 1": {
"name 1" : "abc..",
"location 1" : "abc.."
},
"dict 2": {
"name 2": "abc",
"location 2": "abc"
}
.
.
}

您可以遍历字典的项,并通过从原始键构建子字典键来逐步填充输出字典:

d = {
"name 1": "abc..",
"location 1": "abc..",
"name 2": "abc..",
"location 2": "abc"
}
d2 = dict()                       # empty output
for k,v in d.items():             # go through all keys and values
dk = f"dict {k.split()[-1]}"  # build sub-dict key
d2.setdefault(dk,dict())[k]=v # add key:value to sub-dict
print(d2)
{'dict 1': {'name 1': 'abc..', 'location 1': 'abc..'},
'dict 2': {'name 2': 'abc..', 'location 2': 'abc'}}

如果你被允许使用库,groupby(来自itertools(可以帮助你:

from itertools import groupby
d2 = {dk:dict(g) for dk,g 
in groupby(d.items(),lambda kv:f"dict {kv[0].split()[-1]}")}

对值进行迭代,并相应地分配它们:

new_dict = {}
for k, v in my_dict.items():
if "dict " + k.split()[1] in new_dict:
new_dict["dict " + k.split()[1]][k] = v
else:
new_dict["dict " + k.split()[1]] = {k: v}
>>> new_dict
{ 'dict 1': { 
'name 1': 'abc..', 
'location 1': 'abc..'}, 
'dict 2': { 
'name 2': 'abc..', 
'location 2': 'abc'}
}

最新更新