简体   繁体   中英

How do I save python dictionary into a dataframe if the value of dictionary is tuple of tuples

The structure of dictionary is below:

{ key1 : ((( ' value1', 'value2'),'value3'),'value4')}.

I want value1 to be in 1st row(dataframe) , value2 in 2nd row(dataframe) similarly for all values. for this example, I need to create 4 rows in data frame.

Here is one way to do this:

Input Dict:

{'key1': (((' value1', 'value2'), 'value3'), 'value4')}

Code:

def flatten(seq):
    l = []
    for elt in seq:
        t = type(elt)
        if t is tuple or t is list:
            for elt2 in flatten(elt):
                l.append(elt2)
        else:
            l.append(elt)
    return l
df['val'] = flatten(t)
print(df)

Prints:

       val
0   value1
1   value2
2   value3
3   value4
import pandas as pd

dict_1 = {'key1': ((('value1', 'value2'),'value3'),'value4')}

def nested_value_flatter(input_data, rest_value=[]):
    if type(input_data[0]) == tuple:
        rest_value.append(input_data[-1])
        return nested_value_flatter(input_data[0], rest_value)
    else:
        rest_value.append(input_data[-1])
        rest_value.append(input_data[0])
        return rest_value[::-1]

new_dict = dict()
for k, v in dict_1.items():
    new_dict[k] = nested_value_flatter(v)
new_df = pd.DataFrame(new_dict)

print of new_df is below.

     key1
0  value1
1  value2
2  value3
3  value4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM