Raj Rajeshwari Prasad
Raj Rajeshwari Prasad

Reputation: 334

Extracting values from a dictionary for a respective key

I have a dictionary in a below-mentioned pattern:

dict_one = {1: [2, 3, 4], 2: [3, 4, 4, 5],3 : [2, 5, 6, 6]}

I need to get an output such that for each key I have only one value adjacent to it and then finally I need to create a data frame out of it.

The output would be similar to:

1 2                
1 3                
1 4               
2 3            
2 4             
2 4         
2 5                                       
3 2             
3 5          
3 6           
3 6

Please help me with this.

dict_one = {1: [2, 3, 4], 2: [3, 4, 4, 5],3 : [2, 5, 6, 6]}
df_column = ['key','value']
for key in dict_one.keys():
  value = dict_one.values()
  row = (key,value)
  extended_ground_truth = pd.DataFrame.from_dict(row, orient='index', columns=df_column)
extended_ground_truth.to_csv("extended_ground_truth.csv", index=None)

Upvotes: 0

Views: 45

Answers (2)

tdelaney
tdelaney

Reputation: 77347

You can normalize the data as you iterate the dictionary

df=pd.DataFrame(((key, value[0]) for key,value in dict_one.items()), 
    columns=["key", "value"])

Upvotes: 1

a_guest
a_guest

Reputation: 36249

You can wrap the values in lists, then use DataFrame.from_dict and finally use explode to expand the lists:

pd.DataFrame.from_dict({k: [v] for k, v in dict_one.items()}, orient='index').explode(0)

Upvotes: 0

Related Questions