如何展平嵌套python字典?
我正在尝试展平嵌套字典:如何展平嵌套python字典?,python,dictionary,Python,Dictionary,我正在尝试展平嵌套字典: dict1 = { 'Bob': { 'shepherd': [4, 6, 3], 'collie': [23, 3, 45], 'poodle': [2, 0, 6], }, 'Sarah': { 'shepherd': [1, 2, 3], 'collie': [3, 31, 4], 'poodle': [21, 5, 6], },
dict1 = {
'Bob': {
'shepherd': [4, 6, 3],
'collie': [23, 3, 45],
'poodle': [2, 0, 6],
},
'Sarah': {
'shepherd': [1, 2, 3],
'collie': [3, 31, 4],
'poodle': [21, 5, 6],
},
'Ann': {
'shepherd': [4, 6, 3],
'collie': [23, 3, 45],
'poodle': [2, 10, 8],
}
}
我想显示列表中的所有值:
[4,6,3,23,3,45,2,0,6,1,2,3,…,2,10,8]
我的第一个想法是这样做:
dict_flatted = [ i for name in names.values() for dog in dogs.values() for i in dog]
虽然我得到了错误。我很乐意为您提供如何处理它的提示。您可以使用一个简单的递归函数,如下所示
def flatten(d):
res = [] # Result list
if isinstance(d, dict):
for key, val in d.items():
res.extend(flatten(val))
elif isinstance(d, list):
res = d
else:
raise TypeError("Undefined type for flatten: %s"%type(d))
return res
dict1 = {
'Bob': {
'shepherd': [4, 6, 3],
'collie': [23, 3, 45],
'poodle': [2, 0, 6],
},
'Sarah': {
'shepherd': [1, 2, 3],
'collie': [3, 31, 4],
'poodle': [21, 5, 6],
},
'Ann': {
'shepherd': [4, 6, 3],
'collie': [23, 3, 45],
'poodle': [2, 10, 8],
}
}
print( flatten(dict1) )
您试图使用不存在的变量 用这个
dict_flatted = [ i for names in dict1.values() for dog in names.values() for i in dog]
递归函数可以是单行:
def flatten(d):
return d if isinstance(d, list) else sum((flatten(i) for i in d.values()), [])
注:这是一个的答案,我从@DaewonLee的代码开始,并将其扩展到更多的数据类型和在列表中递归:
def flatten(d):
res = [] # type:list # Result list
if isinstance(d, dict):
for key, val in d.items():
res.extend(flatten(val))
elif isinstance(d, list):
for val in d:
res.extend(flatten(val))
elif isinstance(d, float):
res = [d] # type: List[float]
elif isinstance(d, str):
res = [d] # type: List[str]
elif isinstance(d, int):
res = [d] # type: List[int]
else:
raise TypeError("Undefined type for flatten: %s" % type(d))
return res
你犯了什么错误?你提到了“错误”,但你没有真正描述它。非常非常聪明。很好!谢谢我对代码进行了一些扩展,允许在列表中递归。结果发布在下面。