Home > Net >  I want to grab the Values in a nested dictionary and make it as a fresh dictionary and Later I want
I want to grab the Values in a nested dictionary and make it as a fresh dictionary and Later I want

Time:08-26

Current data

Some_dict = {0: {},
             1: {'A': ['apple']},
             2: {},
             3: {'B': ['orange', 'papaya']},
             4: {'C': ['mango', 'berries', 'grape']}}

I want

my_dict =   { {},
            {'A': ['apple']}, 
            {{},
            {'B': ['orange','papaya']},
            {'C': ['mango', 'berries', 'grape']}}

Then I want to make my_dict as a dataframe:

name fruits
{}
A apple
{}
B orange
B papaya
C mango
C berries
C grape

How can I do that in pandas and in python?

Thanks

CodePudding user response:

Is this what you want ?

 my_fruit_list = []
    for v in d.values():
        if not v:
            my_fruit_list.append([{}, ""])
        else:
            key = list(v.keys())[0]
            my_fruit_list.append([key, v[key]])
    print(my_fruit_list)

CodePudding user response:

you don't need pandas for this, you can just do

new_dictionary_list = [x for x in some_dict.values()]

also dictionary can't be without a key, so you get a list of dictionaries, not a dictionary itself in new_dictionary_list

you can make a data frame using

my_dataframe = pd.DataFrame({'name':[list(x.items())[0][0] for x in new_dictionary_list], 'fruits':[list(x.items())[0][1] for x in new_dictionary_list]})
  • Related