Chique_Code
Chique_Code

Reputation: 1530

Create a new list of dictionaries within a new dictionary in Python

I have a list of dictionaries and need to create a new one that contains new keys and also keys&values from my original dictionary. One of the keys will have to contain a list of dictionaries (those would be the values from original dictionary) My data looks like the following:

data = [{'CloseDate': '2020-05-01',
  'OpportunityID': '1',
  'CustomerID': '10'},
 {'CloseDate': '2020-07-31',
  'OpportunityID': '2',
  'CustomerID': '11'}]

I want my new list of dicts look like this:

new_data = [{'id': '39',
           'Query': [{'records': '40', 'Order Name': '1', 'CustomerID': '10'}]},
           {'id': '39',
           'Query': [{'records': '40', 'Order Name': '2', 'CustomerID': '11'}]}]

I have tried the following:

new_data = []

for item in data: 
    params_dict = {}
    params_dict["id"] = "39"
    params_dict["Query"] = []
    # push new_dicts in params_dict
    new_dict = {}
    new_dict["records"] = "40"
    new_dict["Order Name"] = data["OpportunityID"]
    params_dict.append(new_dict)
    new_data.append(params_dict)

Error: TypeError: list indices must be integers or slices, not str

Upvotes: 1

Views: 1197

Answers (2)

Abdulmecid Pamuk
Abdulmecid Pamuk

Reputation: 39

datas_list=[]
for get_dict in data:
    new_dict={}
    new_dict["id"] = 39
    new_dict['Query']=[]
    other_dictionary={}
    other_dictionary['records']=40
    for values in get_dict:
        if values == "OpportunityID":
            other_dictionary['Order Name'] = get_dict[values]
        if values == "CustomerID" :
            other_dictionary[values] = get_dict[values]
    new_dict["Query"].append(other_dictionary)
    datas_list.append(new_dict)

Upvotes: 2

Joshua Varghese
Joshua Varghese

Reputation: 5202

You were trying to iterate through item and not data inside the loop.
Also you need to append to Query.
Try:

new_data = []

for item in data: 
    params_dict = {}
    params_dict["id"] = "39"
    params_dict["Query"] = []
    new_dict = {} # defined new_dict
    new_dict["records"] = "40"
    new_dict["Order Name"] = item["OpportunityID"] # here it should be item
    params_dict["Query"].append(new_dict)
    new_data.append(params_dict)

Also:

new_data = []

for item in data: 
    params_dict = {}
    params_dict["id"] = "39"
    params_dict["Query"] = [{"records" : "40","Order Name" :item["OpportunityID"] }]
    new_data.append(params_dict)

Upvotes: 1

Related Questions