Thursday, December 4, 2014

Trick & Tip: Flat Dictionary and List

Case 1: flat a dictionary
Sometimes, we may have a dictionary which may have other dictionaries as its values.

Here is a method to flat the complex dictionary to a list, whose first item is the Key from dictionary and rest of items are the Value from dictionary.

Example:
# flat dictionary function
def flatDict(dic):
    def _flatDict(dic, list=[]):
        for k, v in dic.iteritems():
            if isinstance(v, type(dic)):
                _flatDict(v, list)
            else:
                list.append((k, v))
        return list
    return _flatDict(dic)

# create a dictionary
dic = {1:{'a':'red', 'b':'green', 'c':'blue'}, 2:{'L1':[1,2,3], 'L2':[10,20,30], 'L3': [100, 200, 300]}, 3:'this is a test!'}

# print flatten dictionary
print flatDict(dic)


Case 2: flat a list
Also, sometimes, we may meet a list which contents multiple list inside.

Here is a method to flat the complex list to a simple 1-level list.

Example:
# flat list function
def flatList(list):
    def _flatList(list, output=[]):
        for i in list:
            if isinstance(i, type(list)):
                _flatList(i)
            else:
                output.append(i)
        return output
    return _flatList(list)

# create a list
l = [1,2,3, ['a', 'b', ['red', 'yellow', 'blue'], 'c'], 5, 6]

# print out flatten list
print flatList(l)

No comments:

Post a Comment