How to flatten nested python dictionaries?

后端 未结 4 481
清酒与你
清酒与你 2020-12-02 02:12

I\'m trying to flatten the nested dictionary:

dict1 = {
    \'Bob\': {
        \'shepherd\': [4, 6, 3],
        \'collie\': [23, 3, 45],
        \'poodle\':          


        
相关标签:
4条回答
  • 2020-12-02 02:47

    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) )
    
    0 讨论(0)
  • 2020-12-02 02:47

    I started with @DaewonLee's code and extended it to more data types and to recurse within lists:

    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
    
    0 讨论(0)
  • 2020-12-02 02:56

    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]
    
    0 讨论(0)
  • 2020-12-02 03:01

    The recursive function can be single line:

    def flatten(d):
        return d if isinstance(d, list) else sum((flatten(i) for i in d.values()), [])
    

    Nota: was an answer for a duplicate question

    0 讨论(0)
提交回复
热议问题