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

时间:2015-12-02 09:11:49

标签: python-3.x dictionary nested

我还在试图弄清楚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']])

有人可以请给我更多信息或者真的向我解释嵌套字典是如何工作的吗?

2 个答案:

答案 0 :(得分:1)

所以,我希望我能从评论中的对话中做到正确:)

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 comprehensions。您几乎正确:

  

我知道当你使用[]时它是一个列表,()它是一个元组而且是一个字典。

在Python 3中,{}括号有点棘手。它们可用于创建字典和集合!

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':[]}}尝试使用单个字典创建,并且由于字典不可播放,您获得了TypeError异常,通知您某些内容不是hashable :)(集合只能存储可散列的元素)

答案 1 :(得分:0)

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'}