I have a dictionary with IDs and counts:
items_count = {
'1111:271': 111,
'1111:190': 3,
'1231:106': 13,
'1211:104': 111,
'1111:201': 9
}
Key is "category":"id". I want to separate category and put it in another dictionary like:
items_count2 = {
'1111': {'271': 111, '190': 3, '201': 0},
'1231': {'106': 13},
'1211': {'104': 111}
}
but when I do this
items_count2 = {k.split(':')[0]: {k.split(':')[1]: v} for k, v in items_count}
I get error "ValueError: too many values to unpack (expected 2)"
please help to understand, what am I doing wrong?
CodePudding user response:
So first your suggestion should be:
items_count2 = {k.split(':')[0]: {k.split(':')[1]: v} for k, v in items_count.items()}
But this won't be working neither, cause you have multiple k, v per sub-dictionnary.
So below is a way to do, without using dict comprehension:
dct = {
'1111:271': 111,
'1111:190': 3,
'1231:106': 13,
'1211:104': 111,
'1111:201': 9
}
# Initialize your new dict
new_dct = {k.split(':')[0]: {} for k in dct} # Or k in dct.keys()
# Loop through old dict
for k, v in dct.items():
# Set value to top > sub key in new dict
new_dct[k.split(':')[0]][k.split(':')[1]] = v
print(new_dct)
Output:
{'1111': {'271': 111, '190': 3, '201': 9}, '1231': {'106': 13}, '1211': {'104': 111}}
CodePudding user response:
items_count2 = {}
for k, v in items_count.items():
t = items_count2.get(k.split(':')[0],{})
t[k.split(':')[1]] = v
items_count2[k.split(':')[0]] = t
output:
{'1111': {'190': 3, '201': 9, '271': 111},
'1211': {'104': 111},
'1231': {'106': 13}}
{k.split(':')[0]: {k.split(':')[1]: v} for k, v in items_count.items()}
will not give the desired solution because if the key already exists it will be replaced by the current one. So your values will always be a directory of single keys.
CodePudding user response:
Setting up a dictionary with the needed keys is a clearer solution. But if you want to avoid looping, splitting and indexing twice you can create the needed keys on the fly with dict.setdefault
.
items_count = {
'1111:271': 111,
'1111:190': 3,
'1231:106': 13,
'1211:104': 111,
'1111:201': 9
}
items_count2 = {}
for k,v in items_count.items():
s1, s2 = k.split(':')
items_count2.setdefault(s1, {})[s2] = v
items_count2
Output
{'1111': {'190': 3, '201': 9, '271': 111},
'1211': {'104': 111},
'1231': {'106': 13}}