1

I have tried this code:

dictt = {'a':{'d':[4,5,6]},'b':2,'c':3,'d':{'e':[7,8,9]}}
def dic(a):
    lst = []
    for i in a.values():
        if type(i) is dict:
            lst.append(dic(i))
        #lst.append(i)
        else:
            lst.append(i)

    return lst

o/p:

[[[4, 5, 6]], 2, 3, [[7, 8, 9]]]

Expected o/p:

[4,5,6,2,3,7,8,9]
azro
  • 53,056
  • 7
  • 34
  • 70
Manideep
  • 11
  • 2
  • what is the input ? – azro Dec 29 '21 at 16:50
  • Does this answer your question? [How to make a flat list out of a list of lists](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists) – 0stone0 Dec 29 '21 at 16:50

3 Answers3

0

You need to use list.extend to add multiple values in the list, and not the list itself, also handle list type

def dic(a):
    lst = []
    for i in a.values():
        if isinstance(i, dict):
            lst.extend(dic(i))
        elif isinstance(i, list):
            lst.extend(i)
        else:
            lst.append(i)
    return lst

dictt = {'a': {'d': [4, 5, 6]}, 'b': 2, 'c': 3, 'd': {'e': [7, 8, 9]}}
x = dic(dictt)
print(x)  # [4, 5, 6, 2, 3, 7, 8, 9]
azro
  • 53,056
  • 7
  • 34
  • 70
0

I think this is the fastest way

from typing import Iterable 

def flatten(items):
    """Yield items from any nested iterable; see Reference."""
    for x in items:
        if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
            for sub_x in flatten(x):
                yield sub_x
        else:
            yield x


f = lambda v: [f(x) for x in v.values()]  if isinstance(v,dict) else v

list(flatten(f(dictt)))
# [4, 5, 6, 2, 3, 7, 8, 9]

flatten function from: How to make a flat list out of a list of lists

Glauco
  • 1,385
  • 2
  • 10
  • 20
0

Try this:

dictis = {
    'a':{
        'd':[4,5,6]
    }
    ,'b':2
    ,'c':3
    ,'d':{
        'e':[7,8,9]
    }
}

def value(obj):
    for value in obj.values():
        if isinstance(value, dict):
            for value_list in value.values():
                for value in value_list:
                    yield value
        else:
            yield value

listis = [x for x in value(dictis)]

print(listis)
RomanG
  • 230
  • 1
  • 8