【问题标题】:Nested dictionaries in Python: how to make them and how to use them?Python中的嵌套字典:如何制作以及如何使用它们?
【发布时间】:2015-12-02 09:11:49
【问题描述】:

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

有人可以请给我更多信息或真正向我解释嵌套字典的工作原理吗?

【问题讨论】:

  • 请解释{ValueA for each ValueD]} 的含义,因为它不是有效的 Python 代码。
  • @Maciek 这意味着我需要参考 dict_guy['n_customerID']['contacts'] 中存在的联系人来报告客户名称。对于现场联系人,我需要报告关联的客户名称。是不是更明白了还是不清楚?
  • 对不起,还是没听懂 :( 或许写一个你想如何使用你的嵌套字典的例子?像print(dict_guy[1234]['contacts']['guy@host.com']['name'])
  • 您希望contacts 成为字典,我说得对吗?
  • @Maciek 是的,我希望联系人成为字典。对不起,是我,我的解释根本不清楚,我会尝试写一个例子。这里是: print(dict_guy['toto']['contacts']['toto@titi.com']['toto']) 我需要像联系人字段是关键和报告 ['toto' ] 是该键的值。现在更清楚了吗?

标签: python-3.x dictionary nested


【解决方案1】:

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

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

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

这对您有何帮助。如果没有,我们会进一步努力:)

编辑: 关于列表/字典理解。你几乎是对的:

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

{} 括号在 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':[]}} 行试图创建一个 set,其中包含一个字典,并且由于字典不可散列,因此您收到 TypeError 异常通知您某些内容不可散列:) (集合只能存储可散列的元素)

【讨论】:

  • 哦,我明白了!我在谈话的时候弄错了,我尝试了一些改变,但出现了错误 TypeError : unashable type: 'dict' 但现在我明白了!这里是我的错误代码:`如果 n_customerID 不在 dict_guy 中:dict_guy[n_customerID] = { {'clientsName':[],'company':[],'contacts':[]}} `我现在就试试你的代码!比你
  • 嗯...它的工作原理!非常感谢你回答了我所有关于嵌套字典如何工作的问题,我想了好几天我将如何得到这个结果,最后你启发了我的灯笼(不知道我能不能用英语说,这是一个法语表达)。我还有一个问题:如何查看我的 dict 中有多少级别以确保它是正确的?
  • 调试嵌套结构的最佳方法是使用漂亮的打印 - 一种以漂亮的布局显示字典和其他内容的方法。只需import pprintpprint.pprint(the_dictionary)。更多信息在这里:docs.python.org/3.4/library/pprint.html#pprint.pprint
  • @CRC 看看我关于字典理解的编辑,并解释为什么你的代码不起作用:)
  • 非常感谢您的时间和解释!你帮了我很多!
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 2021-09-27
    • 2015-07-03
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多