1

I have a Dataframe with 2 columns as below:

name, type
prod_a, fruit
prod_b, vegetable
prod_c, fruit

I am trying to pass these two columns to the below dict in a loop:

data = {"name": df['name'],
        "accountId": df['type']}

How could I pass values from the Dataframe into the above dict data

1
  • 1
    What is expected output Commented May 6, 2020 at 7:05

2 Answers 2

1

If want loop by each row and create dictionaries separately use:

for x, y in df[['name','type']].values:
    data = {"name": x, "accountId": y}

    print (data)
{'name': 'prod_a', 'accountId': 'fruit'}
{'name': 'prod_b', 'accountId': 'vegetable'}
{'name': 'prod_c', 'accountId': 'fruit'}

Or rename column and use DataFrame.to_dict with r for method records:

for data in df[['name','type']].rename(columns={'type':'accountId'}).to_dict('r'):
    print (data)
{'name': 'prod_a', 'accountId': 'fruit'}
{'name': 'prod_b', 'accountId': 'vegetable'}
{'name': 'prod_c', 'accountId': 'fruit'}

If need same output use DataFrame.to_dict with l for method list:

data = df[['name','type']].rename(columns={'type':'accountId'}).to_dict('l')
print (data)
{'name': ['prod_a', 'prod_b', 'prod_c'], 
 'accountId': ['fruit', 'vegetable', 'fruit']}
Sign up to request clarification or add additional context in comments.

Comments

1

IIUC:

df = pd.DataFrame({
    'name': ['prod_a', 'prod_b', 'prod_c'],
    'type': ['fruit', 'vegetable', 'fruit']
})

data = dict()

for i in list(df.columns):
    data.update({('accountId' if i=='type' else i): list(df[i])})

print(data)
{'name': ['prod_a', 'prod_b', 'prod_c'],
 'accountId': ['fruit', 'vegetable', 'fruit']}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.