How to flatten nested python dictionaries?
You can use a simple recursive function as follows.
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) )
You're trying to use variables that don't exist.
Use this
dict_flatted = [ i for names in dict1.values() for dog in names.values() for i in dog]