【发布时间】: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) <type 'str'> Traceback (most recent call last): File "<pyshell#24>", line 1, in <module> print grab_children(city) File "<pyshell#23>", line 6, in grab_children local_list.extend(grab_children(value)) File "<pyshell#23>", 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