【问题标题】:Python Nested Dictionary to List of ListsPython嵌套字典到列表列表
【发布时间】:2015-10-07 23:40:09
【问题描述】:

我知道这已经被问了很多方法,我尝试阅读其中的大部分,但仍然遇到问题......

我有嵌套字典

city = {'centerLatitude': '40',
 'centerLongitude': '-86',
 'listings': {'A Name Here': {'address': 'the address',
                                     'city': 'acity',
                                     'distance': 'AmillionMiles',
                                     'facility_id': '1234',
                                     'latitude': '34',
                                     'longitude': '-86',
                                     'price': 'tooMuch',
                                     'rating': 'supergreat',
                                     'size': "10'xAz'",
                                     'state': 'XY',
                                     'zip': '50505'}}}

我有这个递归 python 函数(取自另一篇文章)

def grab_children(father):
local_list = []
for key, value in father.iteritems():
    local_list.append(key)
    local_list.extend(grab_children(value))
return local_list

调用函数

print grab_children(city)

我得到了这个错误......而不是一个列表

Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    print grab_children(city)
  File "<pyshell#5>", line 5, in grab_children
    local_list.extend(grab_children(value))
  File "<pyshell#5>", line 3, in grab_children
    for key, value in father.iteritems():
AttributeError: 'str' object has no attribute 'iteritems'

从错误中,我认为函数再次调用自身时使用的 value 发生了一些事情,因为它看起来认为它是一个 str ,是的,没有 .iteritems,但是分块运行它并打印type(value) 它始终是一本字典(应该是这样)。

它适用于这本词典,也取自另一篇文章,我不明白这本词典有什么不同。

city = {'<Part: 1.1>': {'<Part: 1.1.1>': {'<Part: 1.1.1.1>': {}},
                 '<Part: 1.1.2>': {}},
 '<Part: 1.2>': {'<Part: 1.2.1>': {}, '<Part: 1.2.2>': {}},
 '<Part: 1.3>': {}}

我的问题是: 为什么我会收到此错误?我该如何克服错误?如果错误是由于我的字典不同引起的,那有什么不同?

【问题讨论】:

  • 它并不总是字典;如果是,您将不会收到该错误。当您将print(type(value)) 放在local_list.extend() 调用的正上方时,请显示代码和输出。当这让您感到困惑时,请将type 更改为repr
  • 你是对的。 print grab_children(city) &lt;type 'str'&gt; Traceback (most recent call last): File "&lt;pyshell#24&gt;", line 1, in &lt;module&gt; print grab_children(city) File "&lt;pyshell#23&gt;", line 6, in grab_children local_list.extend(grab_children(value)) File "&lt;pyshell#23&gt;", line 3, in grab_children for key, value in father.iteritems(): AttributeError: 'str' object has no attribute 'iteritems' 打印字符串而不是 print(type(value)) print grab_children(city) = -86 所以每个 value 必须是另一个字典。周围的建议?也许是If type(value)='dict'

标签: python list dictionary recursion


【解决方案1】:

请注意示例中的“叶子”都是“{}”。那是一个空的字典。在你的“城市”里,你的叶子是弦。要按书面形式使用此函数,则代替:

city = {'centerLatitude': '40'}

你必须写:

city = { 'centerLatitude': { '40' : {} } }

等等

但是这个问题主题说“列表列表”,这不是您的示例代码所做的。您的示例代码返回一个列表。所以我不太确定你想要什么输出。

【讨论】:

  • 准备 MySQL 数据库表加载的列表列表。嵌套字典在应用程序代码中是无价的,但对于加载 DB 而言意义不大,所以我试图递归地展平它。
  • 除了这个代码只是序列化它。它不会创建嵌套列表。你想要嵌套列表,还是只是一个长列表?您尝试加载的目标表结构是什么?
【解决方案2】:
your function should be changed to check if value is a dict, error  
because you recursive function tries to run iteritems() on a value that isstring. 
if isinstance(value,dict): clause need to be added to this recursive function. 
Otherwise function eventually grabs a string..
         change items() to iteritems() if not python 3

    def grab_children(father):
        local_list = []
        for key, value in father.items():
            local_list.append(key)
            if isinstance(value,dict):
                local_list.extend(grab_children(value))
        return local_list

print(grab_children(city))

['centerLatitude', 'centerLongitude', 'listings', 'A Name Here', 'latitude', 'rating', 'zip', 'longitude', 'facility_id', 'size', 'city', 'distance', 'state', 'address', 'price']

【讨论】:

    【解决方案3】:

    你从不设置停止条件。以下检索所有字典中的所有键:

    def grab_children(father):
        local_list = []
        for key, value in father.iteritems():
            local_list.append(key)
            if type(value) is dict:
                local_list.extend(grab_children(value))
        return local_list
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-30
      • 2021-05-10
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      相关资源
      最近更新 更多