Python 中的嵌套字典:如何制作和使用它们?

Nested dictionaries in Python: how to make them and how to use them?

我仍在努力弄清楚 python 中的嵌套字典是如何工作的。

我知道当您使用 [] 时它是一个列表,() 它是一个元组而 {} 是一个字典。 但是当你想制作一个像这种结构的嵌套字典时(这就是我想要的):

{KeyA :
      {ValueA :
               [KeyB : ValueB],
               [Keyc : ValueC],
               [KeyD : ValueD]},
                              {ValueA for each ValueD]}}

现在我有一个像这样的字典:

{KeyA : {KeyB : [ValueB],
         KeyC : [ValueC],
         KeyD : [ValueD]}}

这是我的代码:

json_file = importation()
    dict_guy = {}                                         
    for key, value in json_file['clients'].items():
        n_customerID = normalization(value['shortname'])
        if n_customerID not in dict_guy:
            dict_guy[n_customerID] = {
                'clientsName':[],
                'company':[],
                'contacts':[], }
        dict_guy[n_customerID]['clientsName'].append(n_customerID)
        dict_guy[n_customerID]['company'].append(normalization(value['name']))
        dict_guy[n_customerID]['contacts'].extend([norma_email(item) for item in v\
alue['contacts']])

谁能给我更多信息或真正向我解释嵌套字典的工作原理?

所以,我希望我能从我们在评论中的谈话中得到正确的答案:)

json_file = importation()
dict_guy = {}                                         
for key, value in json_file['clients'].items():
    n_customerID = normalization(value['shortname'])
    if n_customerID not in dict_guy:
        dict_guy[n_customerID] = {
            'clientsName':[],
            'company':[],
            'contacts':{}, }  # Assign empty dict, not list
    dict_guy[n_customerID]['clientsName'].append(n_customerID)
    dict_guy[n_customerID]['company'].append(normalization(value['name']))
    for item in value['contacts']:
        normalized_email = norma_email(item)
        # Use the contacts dictionary like every other dictionary
        dict_guy[n_customerID]['contacts'][normalized_email] = n_customerID

简单地将字典分配给另一个字典中的键是没有问题的。这就是我在此代码示例中所做的。您可以创建任意深度的字典。

这对您有何帮助。如果没有,我们将进一步研究:)

编辑: 关于 list/dict 理解。你几乎是对的:

I know that when you're using [] it's a list, () it's a tuple and {} a dict.

{}括号在Python3中有点棘手。它们既可以用来创建字典也可以用来创建集合!

a = {}  # a becomes an empty dictionary
a = set()  # a becomes an empty set
a = {1,2,3}  # a becomes a set with 3 values
a = {1: 1, 2: 4, 3: 9}  # a becomes a dictionary with 3 keys
a = {x for x in range(10)}  # a becomes a set with 10 elements
a = {x: x*x for x in range(10)}  # a becomes a dictionary with 10 keys

你的行 dict_guy[n_customerID] = { {'clientsName':[], 'company':[], 'contacts':[]}} 试图创建一个 set 其中只有一个字典,因为字典不可散列,你得到了 TypeError 异常通知你说有些东西是不可散列的:)(集合只能存储可散列的元素)

Check out this page.

example = {'app_url': '', 'models': [{'perms': {'add': True, 'change': True, 
'delete': True}, 'add_url': '/admin/cms/news/add/', 'admin_url': '/admin/cms/news/', 
'name': ''}], 'has_module_perms': True, 'name': u'CMS'}