1
$\begingroup$

I have a dataframe as below:

+----+----------------+-------------+----------------+-----------+
|    |   attribute_one|   value_one |  attribute_two | value_two |
|----+----------------+-------------+----------------+-----------|
|  0 |      male      |    10       |  female        |    15     |
|  1 |     34-45      |    17       |  55-64         |     8     |
|  2 |     graduate   |    32       |  high school   |     5     |
...

I want to convert it into dictionary that gives this output:

{'male': '10', 
 '34-45':'17',
 'graduate':'32'
 'female':'15',
 '55-64': '8', 
 'high school': '5'
 }

How do I do that? I only want attribute columns as keys and their value columns as values.

$\endgroup$
2
  • $\begingroup$ Do let me know if you are satisfied with the answer? If not I will try my best possible way to edit it. Please consider accepting the answer if it answers your question. $\endgroup$ Jun 16 at 12:17
  • 1
    $\begingroup$ Thank you, that worked! $\endgroup$ Jun 16 at 16:09
0
$\begingroup$

Explanation is mentioned in comments

# Created some data like yours
data = {
    'attribute_one':['male','34-45','graduate'],
    'value_one':[10,17,32],
    'attribute_two':['female','55-64','high school'],
    'value_two':[15,8,5]
    }

# Pandas for handling dataframes
import pandas as pd

# Created a dataframe from the given data
df = pd.DataFrame(data)

# Sliced the columns of interests
df1 = df.iloc[:,0:2] # all values of first two columns
df2 = df.iloc[:,2:4] # all values of last two columns

# Final dictionary for the output
your_dict = {}

# Iterate through numpy values of dataframes
for i in df1.to_numpy():
  your_dict[i[0]] = i[1] # populate the dictionary with first dataframe
for i in df2.to_numpy():
  your_dict[i[0]] = i[1] # populate the dictionary with second dataframe

# Your dictionary is ready
print(your_dict)
$\endgroup$
0
$\begingroup$

You may encounter that if an attribute has previously be assigned as a key it will overwrite the dictionary value if the attribute names are not unique.

Storing a list can mitigate this issue.

import pandas as pd

# convert to dict with list of values
def convert_to_dict(df):
    df_dict = {}    # empty dict
    
    for row in df.itertuples():    # itertuples for each row
        
        # make a new list for a new key
        if row.attribute_one not in df_dict:
            df_dict[row.attribute_one] = []
            
        df_dict[row.attribute_one].append(row.value_one)
        
        # make a new list for a new key
        if row.attribute_two not in df_dict:
            df_dict[row.attribute_two] = []
            
        # append value
        df_dict[row.attribute_two] = row.value_two
        
    return df_dict


# Original Data
data = {
    'attribute_one': ['male', '34-45', 'graduate'],
    'value_one': [10, 17, 32],
    'attribute_two': ['female', '55-64', 'high school'],
    'value_two': [15, 8, 5]
    }

# Dataframe
df_data = pd.DataFrame(data)

# Data in dictionary format
data = list_of_dicts(df_data)

print(data)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.