Trouble adding multiple dict k:v pairs

Question:

I’m not understanding how the k:v coding works. I’ve read that k:v pairs the items. k is the key and v is the item. If I want an additional field called ‘cusip’ in addition to ‘lastPrice’, how would I add that? Thanks

response_dict = response.json()
new_dict = {k: v['lastPrice'] for k, v in response_dict.items()}
df = pd.DataFrame.from_dict(new_dict, orient='index', columns=['lastPrice'])
Asked By: user3444610

||

Answers:

Your question is vague, but I would like simulate it maybe useful or close to your issue solution:
Instead of response I defined a new dict with initial values.

import pandas as pd
response_dict = {"price":[10,5,9],"Products":["shoes","clothes","hat"], "lastprices":[5,6,7]}
new_dict = {k: v for k, v in response_dict.items()}
df = pd.DataFrame.from_dict(new_dict)
df

If you keen to add new key with new values just try to modify dictioner: for instance

new_dict["cusip"]=[1,2,3]
df = pd.DataFrame.from_dict(new_dict)
df
Answered By: Jamal Azizbeigi

You just need to build the appropriate tuple.

new_dict = {k: (v['lastPrice'], v['cusIP']) for k, v in response_dict.items()}

In a dictionary comprehension {key_expr: value_expr for ...}, both key_expr and value_expr are allowed to be arbitrary expressions.

Answered By: chepner
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.