I want to grab the Values in a nested dictionary and make it as a fresh dictionary and Later I want to convert it into a df. How Can I do that?

Question:

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

Asked By: oazed lium

||

Answers:

you need the list of values

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

now,

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]})
Answered By: whitespace

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)
Answered By: EnergyBoy

You already got an answer on how to get to my_dict, for creating a DataFrame of your original data you could do the following to create a pair of data for each row:

tmp = []
for key,value in some_dict.items():
    if value:
        tmp.extend([(k,v) for k, vals in value.items() for v in vals])
    else:
        tmp.append(('',''))
print(tmp)

out = pd.DataFrame(res, columns=['name', 'fruits'])
print(out)

Output:

# tmp 

[('', ''), ('A', 'apple'), ('', ''), ('B', 'orange'), ('B', 'papaya'), ('C', 'mango'), ('C', 'berries'), ('C', 'grape')]

# out

  name   fruits
0              
1    A    apple
2              
3    B   orange
4    B   papaya
5    C    mango
6    C  berries
7    C    grape

Answered By: Rabinzel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.