I have a dictionary that looks like this:
dict = {
"name 1": "abc..",
"location 1": "abc..",
"name 2": "abc..",
"location 2": "abc"
.
.
}
My goal is to split it into n other sub dictionaries (depending on the range of integers in the first dictionary), in order to obtain a result like this:
#output
output_dict = {
"dict 1": {
"name 1" : "abc..",
"location 1" : "abc.."
},
"dict 2": {
"name 2": "abc",
"location 2": "abc"
}
.
.
}
CodePudding user response:
You can go through the dictionary's items and progressively fill the output dictionary by building the sub-dictionary keys from the original keys:
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'}}
If you're allowed to use libraries, groupby (from itertools) can help with this:
from itertools import groupby
d2 = {dk:dict(g) for dk,g
in groupby(d.items(),lambda kv:f"dict {kv[0].split()[-1]}")}
CodePudding user response:
Iterate over the values, and assign them accordingly:
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'}
}