Home > Enterprise >  Adding data to dictionary if no corresponding value exist in supporting array
Adding data to dictionary if no corresponding value exist in supporting array

Time:09-28

I have array and dictionary that I want to combine my_array and my_brand_dictand create new mydict dictionary fill that the non-existing date values with 0's.

my_array = ['20201', '20203', '20204', '20205', '20206', '20207', '20208', '20209', '202010', '202011', '202012', '202013', '202014']


my_brand_dict = [{'key': {'Brand': 'Tesla', 'Date': '20203'}, 'Total': 56}, {'key': {'Brand': 'Tesla', 'Date': '20207'}, 'Total': 88}, 
{'key': {'Brand': 'Toyota', 'Date': '202014'}, 'Total': 79}, {'key': {'Brand': 'Toyota', 'Date': '20201'}, 'Total': 49}]


mydict = {
         'name' : "Brand, Dates and sales",
         'labels': my_array,
         'datasets': []
         }

Here is my try to fill mydict with values

temp_dict = dict() 
for i in my_brand_dict:
    temp_dict = {
                'label': i['key']['Brand'],
                'data': [],
                }
    mydict['datasets'].append(temp_dict)
    temp_dict['data'].extend([t['Total'] for t in my_brand_dict if t['key']['Brand'] == temp_dict['label']])

print(mydict)

Which prints :

{'name': 'Brand, Dates and sales', 'labels': ['20201', '20203', '20204', '20205', '20206', '20207', '20208', '20209', '202010', '202011', '202012', '202013', '202014'], 'datasets': [{'label': 'Tesla', 'data': [56, 88]}, {'label': 'Tesla', 'data': [56, 88]}, {'label': 'Toyota', 'data': [79, 49]}, {'label': 'Toyota', 'data': [79, 49]}]}

But I need the output as below for those values added by order and non-exist values to corresponding dates filled with 0s

{'name': 'Brand, Dates and sales', 'labels': ['20201', '20203', '20204', '20205', '20206', '20207', '20208', '20209', '202010', '202011', '202012', '202013', '202014'], 
'datasets': [{'label': 'Tesla', 'data': [0,56,0,0,0,88,0,0,0,0,0,0,0]}, {'label': 'Toyota', 'data': [49,0,0,0,0,0,0,0,0,0,0,0,79]}]}   

CodePudding user response:

Try:

tmp = {}
for d in my_brand_dict:
    tmp.setdefault(d["key"]["Brand"], {})[d["key"]["Date"]] = d["Total"]

mydict = {
    "name": "Brand, Dates and sales",
    "labels": my_array,
    "datasets": [
        {"Label": k, "data": [v.get(vv, 0) for vv in my_array]}
        for k, v in tmp.items()
    ],
}

print(mydict)

Prints:

{
    "name": "Brand, Dates and sales",
    "labels": [
        "20201",
        "20203",
        "20204",
        "20205",
        "20206",
        "20207",
        "20208",
        "20209",
        "202010",
        "202011",
        "202012",
        "202013",
        "202014",
    ],
    "datasets": [
        {"Label": "Tesla", "data": [0, 56, 0, 0, 0, 88, 0, 0, 0, 0, 0, 0, 0]},
        {"Label": "Toyota", "data": [49, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 79]},
    ],
}

CodePudding user response:

I just changed your approach to the problem and it cost an extra O(n) time complexity.

temp_dict = {}
for i in my_brand_dict:


    date = i['key']['Date']
    date_ind = my_array.index(date)
    brand =  i['key']['Brand']
    if brand not in temp_dict:
        temp_dict[brand] = [0]*len(my_array)
        temp_dict[brand][date_ind] = i['Total']
    else:
        temp_dict[brand][date_ind] = i['Total']

I created a new dictionary for each Brand because we would like to create an array for each Brand. The length of that array is known so in the beginning I can create it with zeros. Also, we can find indexes for matching dates and change the values on array. After these steps I just put the info on the mydict:

for dates,brand in temp_dict.items():
    mydict['datasets'].append({'label':brand,'data':dates})

Thus the entire code will be:

my_array = ['20201', '20203', '20204', '20205', '20206', '20207', '20208', '20209', '202010', '202011', '202012', '202013', '202014']


my_brand_dict = [{'key': {'Brand': 'Tesla', 'Date': '20203'}, 'Total': 56}, {'key': {'Brand': 'Tesla', 'Date': '20207'}, 'Total': 88}, 
{'key': {'Brand': 'Toyota', 'Date': '202014'}, 'Total': 79}, {'key': {'Brand': 'Toyota', 'Date': '20201'}, 'Total': 49}]


mydict = {
         'name' : "Brand, Dates and sales",
         'labels': my_array,
         'datasets': []
         }


temp_dict = {}
for i in my_brand_dict:


    date = i['key']['Date']
    date_ind = my_array.index(date)
    brand =  i['key']['Brand']
    if brand not in temp_dict:
        temp_dict[brand] = [0]*len(my_array)
        temp_dict[brand][date_ind] = i['Total']
    else:
        temp_dict[brand][date_ind] = i['Total']

for dates,brand in temp_dict.items():
    mydict['datasets'].append({'label':brand,'data':dates})

print(mydict)
  • Related