Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to repeatedly attach object A for every object B in python?

raw_data_row = { "account_level_data" : {"account_name": "A", "currency" :"USD"} "store_level_data" : {"store_name": "MySotre", "address" :"MyStreet"}, item_values : [{"name": "a", "price" : 30}, {"name": "b", "price" : 40}]}

How can I create an object like that:

new data = 
[{ "account_name": "A", "currency" :"USD", "store_name":"MySotre", "address":"MyStreet", "name": "a", "price" : 30}
{ "account_name": "A", "currency" :"USD", "store_name":"MySotre", "address":"MyStreet", "name": "b", "price" : 40}]

Right now I specify every attribute name and values manually, any way to do it more generic?

new_rows = []
for item in raw_data_row.item_values:
    new_rows.add({"account_name" :raw_data_row.account_level_data.account_name, "currency" :raw_data_row.account_level_data.currency, "store_name" :raw_data_row.store_level_data.store_name, "address" :raw_data_row.store_level_data.address, "name" : item.name, "price":item.price})

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One approach, if the data are dictionaries, in Python 3.9:

raw_data_row = {"account_level_data": {"account_name": "A", "currency": "USD"},
                "store_level_data": {"store_name": "MySotre", "address": "MyStreet"},
                "item_values": [{"name": "a", "price": 30}, {"name": "b", "price": 40}]}

account_data = raw_data_row["account_level_data"]
store_data = raw_data_row["store_level_data"]
res = [value | account_data | store_data for value in raw_data_row["item_values"]]

for row in res:
    print(row)

Output

{'name': 'a', 'price': 30, 'account_name': 'A', 'currency': 'USD', 'store_name': 'MySotre', 'address': 'MyStreet'}
{'name': 'b', 'price': 40, 'account_name': 'A', 'currency': 'USD', 'store_name': 'MySotre', 'address': 'MyStreet'}

For previous Python versions, and a lot whole more see this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading