来自另一本词典的词典

Dictionary from another dictionary

我有一本包含 ID 和计数的字典:

  items_count = {
    '1111:271': 111, 
    '1111:190': 3, 
    '1231:106': 13, 
    '1211:104': 111, 
    '1111:201': 9
    }

键是“类别”:“id”。我想分开类别并将其放入另一个字典中,例如:

items_count2 = {
    '1111': {'271': 111, '190': 3, '201': 0},
    '1231': {'106': 13}, 
    '1211': {'104': 111}
    }

但是当我这样做的时候

items_count2 = {k.split(':')[0]: {k.split(':')[1]: v} for k, v in items_count}

我收到错误 “ValueError:要解压的值太多(预期为 2)”

请帮助理解,我做错了什么?

所以首先你的建议应该是:

items_count2 = {k.split(':')[0]: {k.split(':')[1]: v} for k, v in items_count.items()}

但这也不起作用,因为每个 sub-dictionary.

有多个 k, v

所以下面是一种不使用字典理解的方法:

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)

输出:

{'1111': {'271': 111, '190': 3, '201': 9}, '1231': {'106': 13}, '1211': {'104': 111}}
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

输出:

{'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()}

不会给出所需的解决方案,因为如果密钥已经存在,它将被当前密钥替换。因此,您的值将始终是单个键的目录。

正在使用 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

输出

{'1111': {'190': 3, '201': 9, '271': 111},
 '1211': {'104': 111},
 '1231': {'106': 13}}