Python 正在尝试从以前的词典嵌套词典

Python 正在尝试从以前的词典嵌套词典,python,dictionary,Python,Dictionary,因此,我有以下场景: dictionary=[ {category1:clothes, category2:cheap, category3:10}, {category1:clothes, category2:normal, category3:20}] 我需要一本字典,上面写着{衣服:{便宜:10,普通:20} 我所知道的只是一些单独打印出来的东西 for i in range(len(dictionary)): print({dictionary[i]['category1']:{dic

因此,我有以下场景:

dictionary=[
{category1:clothes, category2:cheap, category3:10},
{category1:clothes, category2:normal, category3:20}]
我需要一本字典,上面写着{衣服:{便宜:10,普通:20} 我所知道的只是一些单独打印出来的东西

for i in range(len(dictionary)):
print({dictionary[i]['category1']:{dictionary[i][category2],dictionary[i][category3]}}
但是它单独打印它们,我不知道如何将它们嵌套在一起,因为这只提供了两个具有我想要的格式的字典,但是嵌套字典只包含第一个列表或第二个列表中的值。我也试过了

[{item['category1']: {'Attribute': attr_key, 'Value': item[attr_key]}}
    for item in dictionary for attr_key in item if attr_key != 'category1']
这是一样的,它提供了更多的行,而我只需要一个cat1字典和其他嵌套在它的字典

raw = {}
for item in dictionary:
    value1 = item.get('category2')
    value2 = item.get('category3')
    raw.update({value1:value2})

data = {}
data[dictionary[0].get('category1')] = raw
输出:

这应该可以做到

import collections

dictionary=[
    {'category1':'clothes', 'category2':'cheap', 'category3':10},
    {'category1':'clothes', 'category2':'normal', 'category3':20}
]

newdict = collections.defaultdict(dict)
for item in dictionary:
  newdict[item['category1']].update({item['category2']: item['category3']})
print(newdict)

请你用简短而中肯的解释来重新表述这个问题好吗。谢谢如果在
字典
中有另一个dict,例如
{category1:costs,category2:normal,category3:20}
如何适合您的情况,我不清楚您的示例谢谢,这很接近,但我需要value字段中的项目是一个单独的字典,而不是一个字典列表。第一次在这里为我释放你的Bankai!:D
import collections

dictionary=[
    {'category1':'clothes', 'category2':'cheap', 'category3':10},
    {'category1':'clothes', 'category2':'normal', 'category3':20}
]

newdict = collections.defaultdict(dict)
for item in dictionary:
  newdict[item['category1']].update({item['category2']: item['category3']})
print(newdict)